in reply to methods for dealing with zero '0' as a string or char

This is a common issue that you should be handling pretty much as you have shown, depending on circumstances. Please see Truth and Falsehood | the first paragraph in Declarations (kinda) or better yet, What is true and false in Perl? (update: or the link (third paragraph) in Eily's post).

Update 1: "Truth and Falsehood" has absquatulated, so had to fix some links.

Update 2:

I find that when I have a string that is just "0" ...
...
I need to use
 if (defined($string)) ...
Just that case might arise if you're reading lines/records from a filehandle with readline($filehandle), e.g., if the last line of the file is "0" and is not newline-terminated (i.e., is just "0"/false and not "0\n"/true). That's why the Perl compiler will "optimise" (if that's the right term) a while-loop condition expression like
    while (my $line = <$fh>) { ... }
to
    while (defined(my $line = <$fh>)) { ... }
c:\@Work\Perl\monks>perl -wMstrict -MO=Deparse,-p -le "my $filename = 'foo'; open my $fh, '<', $filename or die qq{opening '$filename': $!}; ;; while (my $line = <$fh>) { print $line; } " BEGIN { $^W = 1; } BEGIN { $/ = "\n"; $\ = "\n"; } use strict 'refs'; (my $filename = 'foo'); (open(my $fh, '<', $filename) or die("opening '${filename}': $!")); while (defined((my $line = <$fh>))) { do { print($line) }; } -e syntax OK
See O and B::Deparse. Compiled under Perl version 5.8.9.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: methods for dealing with zero '0' as a string or char
by Eily (Monsignor) on Aug 02, 2019 at 13:47 UTC

    I already /msg'd AnomalousMonk about it but maybe a post is a better idea: v5.26 had a section on Truth and Falsehood but not v5.28. I suppose this information is still supposed to be found somewhere in the documentation, but I have no idea where...

    Edit: it is in perldata

      The change that moved the section was 77fae4394, resulting from #115650. (It's a bit of an inconvenience since I've linked to that section quite a few times...)

      Update: I have since posted Truth and Falsehood as a replacement.

Re^2: methods for dealing with zero '0' as a string or char (updated)
by boleary (Scribe) on Aug 21, 2019 at 12:37 UTC

    thanks for the background!