Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Is this "next unless $keys" necessary?

by Plankton (Vicar)
on Jan 13, 2009 at 17:25 UTC ( #736007=perlquestion: print w/replies, xml ) Need Help??

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

... foreach $key (sort keys %{$obj->somehash}) { next unless $key; ...
I would think that the line next unless $key; is not necessary ... right? Or are there situations where this may be needed?

Replies are listed 'Best First'.
Re: Is this "next unless $keys" necessary?
by Fletch (Chancellor) on Jan 13, 2009 at 17:29 UTC

    Can't tell from just that as it depends on if you want to ignore keys which are logically false or not. True or False? A Quick Reference Guide may be of help.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Is this "next unless $keys" necessary?
by Bloodnok (Vicar) on Jan 13, 2009 at 17:31 UTC
    It is necessary if an empty key i.e. '', is legal & expected, but no processing is to be done for it i.e. it has to be avoided when processing all keys.

    It's not too dissimilar to:

    foreach $key (sort grep $_, keys %{$obj->somehash}) { . . .


    Updated to reflect the actual logic - original only tested for empty string ... c/w true/false test as pointed out elsewhere by Fletch.

    A user level that continues to overstate my experience :-))
Re: Is this "next unless $keys" necessary?
by jeffa (Bishop) on Jan 13, 2009 at 17:55 UTC

    The situations where this would be needed are pretty contrived, IMHO. That would mean that someone is using hash keys of value zero or the empty string -- which is certainly allowable, but very contrived:

    my %hash = ( foo => 'bar', 0 => 'baz', '' => 'qux', ); for (sort keys %hash) { next unless $_; print "$_ => $hash{$_}"; } for (sort keys %hash) { print "$_ => $hash{$_}"; }


    (the triplet paradiddle with high-hat)
Re: Is this "next unless $keys" necessary?
by gone2015 (Deacon) on Jan 13, 2009 at 17:58 UTC

    Or, of course, to ignore a key whose value is "0" -- which is the easily forgotten case, until it's burned you enough times to prefer $key eq "".

    (Though  !defined($s) || ($s eq "") is pug-ugly.)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://736007]
Approved by Bloodnok
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2020-12-03 01:47 GMT
Find Nodes?
    Voting Booth?
    How often do you use taint mode?

    Results (49 votes). Check out past polls.