2

Is it possible to use the contents of a variable to reference an element in an array in Perl?

I am creating a variable (see $printelement below) that contains the values "$element[0]", "$element[1]", "$element[2]" and so on.

$counter = 0;
$counter2 = 1; 

$elementlabel = "element";
$opensquarebracket = "[";
$closesquarebracket = "]";

@element = qw(Fast Times at RidgemontHigh); 

print "Array contents:\n\n";

print "This is element[0] : $element[0]\n";
print "This is element[1] : $element[1]\n";
print "This is element[2] : $element[2]\n";
print "This is element[3] : $element[3]\n\n";

while ($counter2 <= 4)
{

   $jk = "\$$elementlabel$opensquarebracket$counter$closesquarebracket";

   $printelement = $jk;
   
   print "This is  element[$counter] : $element[$counter]\n";

   print "This is $printelement : $element[$counter]\n";
   
   print "This is $printelement : $printelement\n\n";

   $counter++;
   $counter2++;
   
}

Instead of printing the contents of the array element, the contents of the variable are printing (see output below):

Array contents:

This is element[0] : Fast
This is element[1] : Times
This is element[2] : at
This is element[3] : RidgemontHigh

This is  element[0] : Fast
This is $element[0] : Fast
This is $element[0] : $element[0]

This is  element[1] : Times
This is $element[1] : Times
This is $element[1] : $element[1]

This is  element[2] : at
This is $element[2] : at
This is $element[2] : $element[2]

This is  element[3] : RidgemontHigh
This is $element[3] : RidgemontHigh
This is $element[3] : $element[3]

Thanks in advance. Your help is greatly appreciated.

2
  • 1
    Tip: for my $counter (0..$#elements) { ... } would be far better than $counter = 0; $counter2 = 1; while ($counter2 <= 4) { ... $counter++; $counter2++; } Commented Jul 23, 2020 at 5:58
  • 1
    Tip: ALWAYS use use strict; use warnings; Commented Jul 23, 2020 at 5:58

1 Answer 1

2

To execute a string that consists of Perl code, you can use eval EXPR.

my $x = eval($printelement);
die $@ if $@;
Sign up to request clarification or add additional context in comments.

Comments

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.