Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: What I Most Recently Learned in Perl, But Should Have Already Known

by wfsp (Abbot)
on Aug 17, 2006 at 11:03 UTC ( [id://567884]=note: print w/replies, xml ) Need Help??


in reply to What I Most Recently Learned in Perl, But Should Have Already Known

Using a foreach loop on an AoH creates an alias of the hash which goes out of scope after the loop.

#!/usr/bin/perl use strict; use warnings; my $recs = [ # short records for brevity {id => 1}, {id => 2}, {id => 3}, ]; my $rec; for $rec (@{$recs}){ # $rec is an alias... if ($rec->{id} == 1){ last; } } # ... which is now out of scope :-( print "$rec->{id}\n"; # Use of uninitialized value... # what I should have done ($rec) = grep {$_->{id} == 1} @{$recs}; print "$rec->{id}\n"; # 1
  • Comment on Re: What I Most Recently Learned in Perl, But Should Have Already Known
  • Download Code

Replies are listed 'Best First'.
Re^2: What I Most Recently Learned in Perl, But Should Have Already Known
by pKai (Priest) on Aug 17, 2006 at 22:55 UTC
    # $rec is an alias...

    It's the previously declared lexical, implicitly localized. See perldoc perlsyn...

    Shorter example, without the need to blame AoH for the problem:

    my $var = 4; for $var (1 .. 9) { last if $var == 7; } print $var; # prints: 4

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-26 01:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found