Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Is this "next unless $keys" necessary?

by Plankton (Vicar)
on Jan 13, 2009 at 17:25 UTC ( [id://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 (Bishop) 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}) { . . .

    Update:

    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{$_}"; }

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-03-28 17:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found