Re: change one line in a large fine

[email protected] Sun, 20 Nov 2022 23:45:22 +0000
Newsgroups gmane.comp.lang.perl.beginners
Message-ID <[email protected]>
please see this ops:

$ echo -n 0 > 1.txt

1.txt has only one line without eof.

but the script below still got true for matching 0.

$ cat test.pl 
use strict;

open HD,"1.txt" or die $!;
while(<HD>){
  print "hi";
}


which will print hi.

can you help further?


November 20, 2022 at 11:19 PM, "Kang-min Liu" <[email protected]> wrote:


> 
> [email protected] writes:
> 
> > 
> > May i ask a question about reading file?
> > 
> >  while(0){ print 'hi' }
> > 
> >  Will never print hi.
> > 
> >  cat 1.txt:
> >  0
> > 
> >  open FH, '1.txt' or die;
> >  while(<FH>) { print 'hi' }
> > 
> >  This will print hi.
> > 
> >  Since $_ == 0 here, why while become true?
> > 
> 
> This seems to be more about what are true-y and what are false-y.
> 
> If the content of 1.txt is one line containing a character "0" follewed
> by the newline character, that means doing <FH> would make $_
> contain "0\n", that's two characters, not one.
> 
> "0\n" would be a true-y value while it is still numerically the same as
> 0 when testing with the operator `==`. The `==` operator always convert
> both of its operants to numerical values before doing the
> comparison. Similarly `eq` operator always converts both operants to
> string before doing the comparison.
> 
> There are a lot of ways to make variables being numerically 0 while also
> being a true-y value. Most of them are strings with leading zeros. You
> could try editing the following program to play around:
> 
>  use strict;
> 
>  $_ = "0\n";
> 
>  print "true-y\n" if $_;
> 
>  print "== 0\n" if $_ == 0;
>  print "eq 0\n" if $_ eq 0;
> 
>  print "eq \"0\"\n" if $_ eq "0";
>  print "== \"0\"\n" if $_ == "0";
> 
> There are also a lot of values with leading "0" which would be true-y,
> but fail all 4 other if-s. :-)
> 
> BTW, really, don't actually write `eq 0` or `== "0"`, they just look weird.
> 
> --
> Cheers,
> Kang-min Liu
> 
> -- 
> To unsubscribe, e-mail: [email protected]
> For additional commands, e-mail: [email protected]
> http://learn.perl.org/
>

-- 
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/