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

Re: Closure Over Scalar?

by BillKSmith (Prior)
on Feb 18, 2021 at 20:29 UTC ( #11128540=note: print w/replies, xml ) Need Help??

in reply to Closure Over Scalar?

This seems to be what use feature 'state' is made for.
#!/usr/bin/env perl # demo of closure around sub, with persistent string use strict; use warnings; use feature 'state'; for my $q ('a'..'g') { do_something($q); print "Done computing\n" } sub do_something { state $FIXED_STRING = 'fixed_string'; state %persistent; my $x = $_[0]; $persistent{$x}{$FIXED_STRING} = rand; END { for my $k (keys %persistent) { print "$k: $persistent{$k}{$FIXED_STRING}\n"; } } }

Replies are listed 'Best First'.
Re^2: Closure Over Scalar?
by QM (Parson) on Feb 19, 2021 at 14:25 UTC
    This seems to be what use feature 'state' is made for.
    Yes, state has fallen out of my lexicon from disuse. A very good point, I don't need a closure, and the assignment happens as expected!

    Quantum Mechanics: The dreams stuff is made of

      It is not an issue in your example, but could be in your production code. Initialization of state hash and array variables was not available before v5.28.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2021-04-15 03:06 GMT
Find Nodes?
    Voting Booth?

    No recent polls found