-3

I have below expression in perl

@var1 = [($a, $b)]

Can anyone help me to deference the value stored in var1.

Raghvendra
  • 124
  • 1
  • 10

2 Answers2

4

@var1 is an array containing a single element. That single element ($var[0]) contains a reference to another array. That referenced array has two elements, containing the values of the variables $a and $b.

So $var[0] contains an array reference. To get from an array reference to the elements of the referenced array, we use the look-up arrow, ->.

print $var[0]->[0]; # The first element in the referenced array
print $var[0]->[1]; # The second element in the referenced array

There's one extra syntactic nicety that we can use here. When we have two sets of look-up brackets separated by only a look-up arrow, we can omit that arrow. So the expressions become.

print $var[0][0];
print $var[0][1];

Two points about your code:

  • $a and $b are special variables that are used in sorting subroutines. It is a bad idea to use them anywhere else.
  • In your original assignment expression (@var1 = [($a, $b)]) the parentheses are unnecessary. Just @var1 = [$a, $b] would have done the same thing.
Dave Cross
  • 68,119
  • 3
  • 51
  • 97
1

@var1 is an array of an array. So its only content is another array containing two values, $a and $b.

$a2 = $var1[0][0];
$b2 = $var1[0][1];
Psi
  • 6,387
  • 3
  • 16
  • 26