Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Printing from a hash table

by BillKSmith (Monsignor)
on Jun 03, 2020 at 03:57 UTC ( [id://11117623]=note: print w/replies, xml ) Need Help??


in reply to Printing from a hash table

When you need both the key and the value of a hash in a loop, the function each is convenient.
use strict; use warnings; my %birthdays = ( Fred => 'June 1', Ray => 'May 31', Glenn => 'May 27', Bob => 'August 28', Jim => '', Paul => undef, ); while (my ($name, $B_day) = each %birthdays) { next if !defined $B_day or $B_day eq ''; printf "%9s : %-9s\n", $name, $B_day; }

Output:>/

Glenn : May 27 Fred : June 1 Ray : May 31 Bob : August 28
Bill

Replies are listed 'Best First'.
Re^2: Printing from a hash table
by perlfan (Vicar) on Jun 03, 2020 at 04:20 UTC
    Careful, each has a nasty gotcha - iterator state! I personally never use it because of this and having been bit by it a few times.
    The iterator used by each is attached to the hash or array, and is shared between all iteration operations applied to the same hash or array. Thus all uses of each on a single hash or array advance the same iterator location. All uses of each are also subject to having the iterator reset by any use of keys or values on the same hash or array, or by the hash (but not array) being referenced in list context. This makes each-based loops quite fragile: it is easy to arrive at such a loop with the iterator already part way through the object, or to accidentally clobber the iterator state during execution of the loop body. It's easy enough to explicitly reset the iterator before starting a loop, but there is no way to insulate the iterator state used by a loop from the iterator state used by anything else that might execute during the loop body. To avoid these problems, use a foreach loop rather than while-each.
    

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2024-04-25 11:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found