0

Suppose I have this piece of code.

It has an array 'arr' storing the names of other arrays like 'et', 'rt' etc...

    #!/usr/bin/perl
    $\="\n";
    @arr = ("$et", "\$rt", "\$ee", "\$re", "\$ec", "\$epc", "\$rc", "\$rpc", "\$euc", "\$ruc", "\$ekc", "\$rkc");
    @et = (100, 1000, 1100, 1200, 200, 300, 400, 500, 600, 700, 800, 900);
    .
    .
    .

And other arrays rt, ee similarly defined..

How do I access say $et[2]? I've tried $arr[0][2], $($arr[0])[2] and many other variations but nothing seems to work. Any solution?

1
  • Check ARRAYS OF ARRAYS, HASHES OF ARRAYS, ARRAYS OF HASHES, HASHES OF HASHES => perldoc.perl.org/perldsc.html Commented Jan 7, 2014 at 8:38

2 Answers 2

2

It's a bad idea to work this way. What you probably want is not to store the names of other arrays, but references to it, e.g.

my @et = ( 100,1000,1100,1200,... );
my @arr = ( \@et,... )

then you can access the second element from @et using @arr with $arr[0][1]:

  • $arr[0] -> \@et (reference to @et)
  • $arr[0][1] -> second element of @et

often you see instead people write $arr[0]->[1], which is exactly the same, only 2 bytes longer :)

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

Comments

2

You don't use use strict; (or, at least, not use strict refs;).

You need ${$arr[0]}[2], but you store the plain name ("et") in @arr:

@arr = ("et", "rt",);
@et = (100, 1000, 1100, 1200, 200, 300, 400, 500, 600, 700, 800, 900);

print ${$arr[0]}[2], "\n";

It isn't good style, though. You'd be better off using a hash indexed by 'array name' with the arrays (or array refs) as the value associated with the key:

my %arr = ( "et" => [100, 1000, 1100], "rt" => [200, 2000, 2200] );

print $arr{et}->[2], "\n";

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.