in reply to Re^2: Aren't there code refs as well as function refs?
in thread Aren't there code refs as well as function refs?

G'day harangzsolt33,

"I would like to point out a distinction."

You have failed to do that. The 108 lines of code that you've posted contain no references to functions, subroutines, or any other code.

Calling a variable $CODE_REF does not make it a coderef. $CODE_REF is not any kind of reference; it's just a string:

$ perl -MO=Deparse -e 'my $CODE_REF = \"if (\$c == 64) { \$MODE = prin +t \"\\n\"; }" . " else { print chr(\$MODE = \$MODE & 1 ? 32 : 35) x \ +$c; } ";' my $CODE_REF = 'SCALAR(0xa00038be0) else { print chr($MODE = $MODE & 1 + ? 32 : 35) x $c; } '; -e syntax OK

You can explicitly check it yourself:

$ perl -e 'my $CODE_REF = \"if (\$c == 64) { \$MODE = print \"\\n\"; } +" . " else { print chr(\$MODE = \$MODE & 1 ? 32 : 35) x \$c; } "; my +$ref = ref $code_ref; print $ref ? $ref : "not a ref";' not a ref

Or let Perl do it for you:

$ perl -Mstrict -e 'my $CODE_REF = \"if (\$c == 64) { \$MODE = print \ +"\\n\"; }" . " else { print chr(\$MODE = \$MODE & 1 ? 32 : 35) x \$c; + } "; $CODE_REF->();' Can't use string ("SCALAR(0xa00038c70) else { print"...) as a subrouti +ne ref while "strict refs" in use at -e line 1.
"Is there any other way to do it?"

You can modify a caller's variables by passing references to those variables. Here's a very simple example:

#!/usr/bin/env perl use strict; use warnings; my ($x, $y) = qw{X Y}; print "BEFORE:\n"; print "\$x[$x] \$y[$y]\n"; mod_callers_vars(\$x, \$y); print "AFTER:\n"; print "\$x[$x] \$y[$y]\n"; sub mod_callers_vars { my ($x_ref, $y_ref) = @_; $$x_ref = 'A'; $$y_ref = 'B'; return; }

Output:

BEFORE: $x[X] $y[Y] AFTER: $x[A] $y[B]

I see LanX has shown you how to use closures (which could be appropriate for more complex scenarios).

In "Re^4: Aren't there code refs as well as function refs?", you wrote:

"... you decide to call each function with 30 or so arguments."

That would be a very poor decision. Instead, use a single hashref argument.

— Ken

Replies are listed 'Best First'.
Re^4: Aren't there code refs as well as function refs?
by LanX (Saint) on Mar 05, 2023 at 00:45 UTC
    > You can modify a caller's variables by passing references to those variables.

    here a 2 variants with aliases instead of passing references

    # https://perlmonks.org/?node_id=11150731 use strict; use warnings; my ($x, $y) = qw{X Y}; print "BEFORE:\n"; print "\$x[$x] \$y[$y]\n"; mod_callers_vars1($x, $y); print "AFTER1:\n"; print "\$x[$x] \$y[$y]\n"; mod_callers_vars2($x, $y); print "AFTER2:\n"; print "\$x[$x] \$y[$y]\n"; sub mod_callers_vars1 { @_[0,1] = ('A','B'); return; } sub mod_callers_vars2 { my ($x_ref, $y_ref) = \(@_); $$x_ref = 'C'; $$y_ref = 'D'; return; }

    --->

    BEFORE: $x[X] $y[Y] AFTER1: $x[A] $y[B] AFTER2: $x[C] $y[D]

    Cheers Rolf
    (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
    Wikisyntax for the Monastery