Re: [NEWBIE] Trivial?



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
.



Relevant Pages

  • Re: awesome help, but, a question
    ... sample program, since I am new to perl, I am having trouble ... If all ranges in the string were processed correctly, it's empty, so return TRUE if it's empty and FALSE if it's not empty. ... I know it's complicated because it took me at least a couple of hours to figure it out, and I used some non-trivial features to do it. ...
    (perl.beginners)
  • problem with perl + thread + extension
    ... I use perl and write an extension as wrapper for ... ret = ProcError (aTHX_ context, ... create an error: the argument stack is empty and: ...
    (comp.lang.perl.misc)
  • Re: Learning Perl
    ... UG> and thousands of experienced perl hackers never thought of ... empty list and a null value at the same time. ... hashes are so different from Lisp structures, though, it just doesn't ... Do you mean that since the empty set is a member of all sets, ...
    (comp.lang.perl.misc)
  • Re: readdir formulated badly? gives wrong count
    ... seems perl should say something about this. ... will invoke a warning while the empty AR in a for loop will not. ... The flow of the program through conditionals and ...
    (perl.beginners)
  • Re: help... this perl is different... null values are crashing my script.
    ... JS> environment is empty, the second line will crash. ... there is no empty nor null value in perl. ... if warnings are enabled. ...
    (comp.lang.perl.misc)