Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^4: Loop once on condition 1, many times on cond. 2?

by punch_card_don (Curate)
on Oct 09, 2008 at 15:37 UTC ( [id://716242]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Loop once on condition 1, many times on cond. 2?
in thread Loop once on condition 1, many times on cond. 2?

Excellent, thanks.

I'll read up on this notation.




Time flies like an arrow. Fruit flies like a banana.
  • Comment on Re^4: Loop once on condition 1, many times on cond. 2?

Replies are listed 'Best First'.
Re^5: Loop once on condition 1, many times on cond. 2?
by AnomalousMonk (Archbishop) on Oct 09, 2008 at 18:19 UTC
    Some maintainability may be gained at the cost of some concision by separating out loop list generation:
    my @keys_to_process = $x eq 'key_1' ? keys %my_hash : exists $my_hash{$x} ? ($x) : () # default - nothing to do ; foreach $key (@keys_to_process) { do_something_with($key); }
    Further, because the above will loop over all keys if $x eq 'key_1' is true even if 'key_1' does not exist in the hash (which may or may not be what you want: Your Logic May Vary), perhaps re-order list generation:
    my @keys_to_process = ! exists $my_hash{$x} ? () : $x eq 'key_1' ? keys %my_hash : ($x) ;
Re^5: Loop once on condition 1, many times on cond. 2?
by gone2015 (Deacon) on Oct 09, 2008 at 16:57 UTC

    You can chain these suckers... so to ensure you do nothing if $x doesn't appear in %my_hash:

    foreach $key ( ($x eq 'key_1') ? keys %my_hash : exists $my_hash($x) +? $x : () ) { do a bunch of stuff }
    noting that if $x does not exist, what you want is an empty list.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-23 11:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found