Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

How do tell Perl to break only on undef?

by myuserid7 (Scribe)
on Oct 22, 2017 at 09:18 UTC ( [id://1201831]=perlquestion: print w/replies, xml ) Need Help??

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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1201831]
Approved by Athanasius
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2024-04-19 01:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found