http://qs1969.pair.com?node_id=1201831

myuserid7 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, while working on a package I ran into a problem for which I could not find a pretty solution. I broke things down to come up with the example code below to demonstrate my issue. When this script is executed, it will print only "12568", because 0 is considered as false and this breaks the while loop. Now I could use while(1) and add some more lines to check $i for undef and then do a "last", but the package is supposed to be used by others so I want to keep it as simple as possible. What would be a pretty/easy way to make while only treat undef as a breaking argument?

#!/usr/bin/perl -w use strict; use warnings; my $t = test->new(); while (my $i = $t->get) { print $i; }; package test; use strict; use warnings; my @list; sub new { my $self = shift; my $this = {}; @list = ( 1, 2, 5, 6, 8, 0, 9 ); bless($this, $self); return($this); }; sub get { return(shift(@list)); }; 1;

Replies are listed 'Best First'.
Re: How do tell Perl to break only on undef?
by choroba (Cardinal) on Oct 22, 2017 at 09:20 UTC
    That's why Perl has defined:
    while (defined( my $i = $t->get )) { print $i; };
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      I cannot believe I forgot defined
      Thanks!