in reply to re-using a hash reference (was: Mar)

A fairly common Perl idiom is:
# Localize expression into $_ using a single-value 'for'. # $_ is default for many Perl functions. for ($some_very_long_expression_you_will_use_more_than_once) { die unless defined; die unless /^expected/; do_something($_); do_something_else($_); }
Your code becomes:
for ( $hash1->{'a'}->{'b'}->{'c'} ) { $hash2->{'bob'} = $_ if defined; }

Replies are listed 'Best First'.
Re: Idiom: Localize with 'for'
by tadman (Prior) on Jun 09, 2002 at 05:36 UTC
    I'd use this more often, but it kind of feels strange. Like wearing shoes that are too big, perhaps. You're looping one thing, which means that this is an un-loop. In fact, it's really just a fancy way of making a reference:
    for my $foo ($_[0]->{bar}->{baz}) { if ($foo->{gronk}) { $foo = { glarb => "oorgle" }; } }
    It's a lot easier than making $$foo reference that thing and then constantly dereferencing it.