Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Explaining @{ [ %hash ] }

by jarich (Curate)
on Sep 04, 2003 at 03:55 UTC ( [id://288787]=note: print w/replies, xml ) Need Help??


in reply to Re: Re: Hashes: Deleting elements while iterating - deleting phantoms?
in thread Hashes: Deleting elements while iterating

if some kind soul would give an explanation of why the third antirice loop works, i could sleep easy. easier...

foreach my $key ( @{[%hash]} ) { print $key; delete $hash{$key}; }

What antirice has done here is to take a copy of the hash as a list. After this, interating over the copy means that every second delete attempts to delete a key that never existed in the hash and fails quietly while all the others succeed.

No doubt you're confused by the

@{[%hash]}
bit.

Enclosing something in square brackets in Perl takes it in list context. It also generates an array reference to that. So %hash here is copied into an annoymous array. This is then deferenced by the @{}s because foreach expects a list, not a reference.

Does this help?

All the best,

jarich

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2024-04-25 08:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found