-1

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"

tavor999
  • 447
  • 6
  • 25

3 Answers3

3

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.

Miller
  • 34,962
  • 4
  • 39
  • 60
  • Thanks for fast response. adding the "no strict" does allow it to continue without dying. I realize hashes are the obvious solution here but for other reasons I am curious if there is a solution using scalars/refs. Still testing but using "no strict" still isn't finding it using ${$color} – tavor999 Jun 04 '14 at 21:57
  • 4
    This is one area where curiosity didn't just kill the cat. Honestly, if I found a coder using such a construct, I'd fire them. There are not enough ways to say, just don't do that. – Miller Jun 04 '14 at 22:03
  • Thanks. I wish I could up your response but I don't have enough cred yet. – tavor999 Jun 05 '14 at 01:32
2

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};
tobyink
  • 13,478
  • 1
  • 23
  • 35
0

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:

simbabque
  • 53,749
  • 8
  • 73
  • 136