Question

I am trying to do some scalar reference work. Here is a simplified version of what I am trying to accomplish. I am currently using perl 5.10.1.

Notes:

*color is dynamically obtained

*trying to get a say 100, or the red value

*I realize this is much easier done with a hash but how can I do it with scalars?

$red = 100;
$blue = 150;
$green = 200;

$color = "red";

say ${$color};

Current error = SCALAR ref while "strict refs"

Was it helpful?

Solution

The error you are receiving is because of use strict. You need to turn off strict refs.

no strict 'refs';
say ${"$color"}; # "" are optional, I want to show it's about the string

Edit: Note that this only works on global variables. So you need to declare them with our or use vars instead of my. This is documented in perlfaq7 and shows why it is not a good idea to use variables to name other variables.


It's OK to turn off a strict feature in certain cases. But remember that it is good practice to contain it inside a very limited scope so it does not affect parts of your program that better not have this turned off.

use strict;
use warnings;
use feature 'say';

our $red = 100;
our $blue = 150;
our $green = 200;

my $color = "red";
{
  no strict 'refs'; # we need this to say the right color
  say ${$color};
}
# more stuff here

See also:

OTHER TIPS

Use a hash, that's what they're for:

my %color_value = (
    red => 100,
    blue => 150,
    green => 200,
);

$color = "red";

say $color_value{$color};

Otherwise, your error was reported because you just forgot to do no strict "refs";. But please please don't do that.

In addition to the answers already given...

use strict;
use warnings;
use feature qw( say );

my $red = 100;
my $blue = 150;
my $green = 200;

my $color = \$red;

say ${$color};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top