Re: [NEWBIE] Trivial?
- From: "John W. Krahn" <dummy@xxxxxxxxxxx>
- Date: Sat, 29 Sep 2007 06:53:30 GMT
El Bandolero wrote:
I'm solving an exercise studying on a tutorial
The task is to print the (empty or not) lines of a file numbering only the
non empty ones.
How the h### is possible that the following code gives the same result if I
change line 9 with the opposite condition?
if (!$lines[$i]=="")
1 #!/usr/bin/perl
2 #
3 $file = 'C:\Perl\html\Artistic.txt'; 4 open(PIP, $file); 5 @lines = <PIP>; 6 close(PIP); 7 for ($i=0;$i <= @lines;++$i)
8 {
9 if ($lines[$i]=="")
10 {print $i." ".$lines[$i]};
11 }
How is it possible? The expressions $lines[$i] and !$lines[$i] are both *numerically* equal to the string "", unless the contents of $lines[$i] start with numerical digits. In Perl, any non-numeric string has the numeric value of zero so 0 == 0 is always true.
You should enable warnings and perl would have informed you that you are using numerical comparison on strings instead of numbers.
#!/usr/bin/perl
use warnings;
use strict;
my $file = 'C:/Perl/html/Artistic.txt';
open my $PIP, '<', $file or die "Cannot open '$file' $!";
while ( <$PIP> ) {
print $. - 1, " $_" if /^$/;
}
close $PIP;
__END__
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
.
- References:
- [NEWBIE] Trivial?
- From: El Bandolero
- [NEWBIE] Trivial?
- Prev by Date: Re: [NEWBIE] Trivial?
- Next by Date: Re: string concatentation vs. interpolation: which one is more optimal?
- Previous by thread: Re: [NEWBIE] Trivial?
- Next by thread: FAQ 5.1 How do I flush/unbuffer an output filehandle? Why must I do this?
- Index(es):
Relevant Pages
|