in reply to how to "rename" a global argument in subroutine?

Parse by reference:

my $red = undef; my $green = undef; my $blue = undef; sub change{ my($color1, $value1, $color2, $value2, $color3, $value3) = @_; ${$color1} = $value1; ${$color2} = $value2; # maybe: if defined $value2; ${$color3} = $value3; } change(\$red, 42, \$green, 255, \$blue, 11); print "($blue)";

Alternative:

#!/usr/bin/perl use strict; use warnings; my %COLORS = ( red => undef, green => undef, blue => undef, ); sub change2{ my($R) = @_; my %H = %$R; for my $key (keys %H){ $COLORS{$key} = $H{$key}; } } change2( {red=>5, green=>6, blue=>7} ); print $COLORS{red};

Replies are listed 'Best First'.
Re^2: how to "rename" a global argument in subroutine?
by FreeBeerReekingMonk (Deacon) on Aug 11, 2015 at 18:26 UTC

    And if those RGB variables are "static", then why not put them into a nice hash?

    #!/usr/bin/perl use strict; use warnings; my %COLORS = ( red => undef, green => undef, blue => undef, ); sub change{ my($R,$G,$B) = @_; $COLORS{red} = $R; $COLORS{green} = $G; $COLORS{blue} = $B; } change(11); print $COLORS{red};
      I hadn't known about hashing! Thanks for your nice post!
Re^2: how to "rename" a global argument in subroutine?
by Anonymous Monk on Aug 11, 2015 at 18:42 UTC

    Thank you for your answer! ...although I'm now having some other issue related..

    Does "parsing by reference" make that a symbolic link? Because later when I try to access $red 's value I get the following error.

    "Can't use string ("red") as a SCALAR ref while "strict refs"

    Would you have any other advice on how I could go about resolving this? Much appreciated.

      Yes, a reference is a "symbolic link", to point to the value you need to either use the arrow or typecast it. For example:

      #!/usr/bin/perl use strict; use warnings; my $red = 23; my $also_red = \$red; ${ $also_red } = 12; # typecast to scalar using ${} print "$red is actually $$also_red"; # this also works