Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Closure Over Scalar?

by ikegami (Patriarch)
on Feb 18, 2021 at 23:36 UTC ( [id://11128544]=note: print w/replies, xml ) Need Help??


in reply to Closure Over Scalar?

The assignment to $FIXED_STRING is found after the sub call. It hasn't been executed when the sub is called.

(And using a my var without first executing the my statement is undefined behaviour.)

Use

{ my $FIXED_STRING = 'fixed_string'; my %persistent; sub do_something { my $x = $_[0]; $persistent{$x}{$FIXED_STRING} = rand; END { for my $k (keys %persistent) { print "$k: $persistent{$k}{$FIXED_STRING}\n"; } } } } for my $q ('a'..'g') { do_something($q); print "Done computing\n" }

or use state.

use feature qw( state ); for my $q ('a'..'g') { do_something($q); print "Done computing\n" } sub do_something { my $x = $_[0]; state $FIXED_STRING = 'fixed_string'; state $persistent = {}; $persistent->{$x}{$FIXED_STRING} = rand; END { for my $k (keys %$persistent) { print "$k: $persistent->{$k}{$FIXED_STRING}\n"; } } }

Seeking work! You can reach me at ikegami@adaelis.com

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11128544]
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: (3)
As of 2024-06-16 21:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.