1

I know this is a no-no...and yes, I still want to do it or at least know how to do it. I would like to set the value of a variable in Perl for which the name is dynamically created (I am looping through different arrays of strings). I know I could do it rather straightforwardly with a hash array, but I'm just curious how you do this with a scalar variable, e.g.

$time  = 't0';
$color = 'blue';

I want to create the variable

$bluet0 = 1;

I've tried

${time.$color} = 1 

but that doesn't work.

5
  • stackoverflow.com/a/47335538/4251338 Commented Sep 22, 2022 at 13:44
  • 2
    @ssr1012, That Q&A isn't even about Perl!? Commented Sep 22, 2022 at 13:53
  • It would work except time is a builtin perl function. Use ${"time" . $color} or ${"time$color"}. Commented Sep 22, 2022 at 13:54
  • @ikegami: Really I am not understand your question. However my comment and the OP's question both are same I thought. Your opinion please? Commented Sep 24, 2022 at 11:33
  • I didn't ask any question!? Commented Sep 28, 2022 at 1:01

1 Answer 1

4

Replace

${ time . $color } = 1;

with

no strict qw( refs );

${ $color . $time } = 1;

Like you said, this is something to avoid.

Sign up to request clarification or add additional context in comments.

3 Comments

And just to add to ikegami's solution (thank you!), which I had tried as well and the reason why it didn't work for me was that I was also initializing my variable with my, i.e. my $bluet0 = 0; before that -- the no strict line gave me the hint to remove that.
Symbolic references can only reference package variables. You'd need PadWalker for lexicals.
Had wrong stricture. It's no strict qw( refs ); that's needed. Fixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.