isakbob
isakbob

Reputation: 1549

How do I pass in the name of an array index in perl?

Background

I have these four lines of code that I am trying to extract into one function:

my @firstList = split /\s+/, $doubleArray{A_I}{B_I};
@firstList = shuffle(@firstList);
my @secondList = split /\s+/, $doubleArray{A_I}{C_I};
@secondList = shuffle(@secondList);

Since the only functional difference is the second index of the two dimensional array , I wanted to make it so that the second index ("B_I" and "C_I") are passed into a function.

Proposed solution

In other words I want to make a function like the one below:

my funkyFunc($){
     my $index = shift;
     my @list = split /\s+/, $doubleArray{A_I}{$index};
     @list = shuffle(@list);
     return @list;
}

I would intend to use it as such:

my @firstList = funkyFunc("B_I");
my @secondList = funkyFunc("C_I");

However, I'm unsure as to how perl would interpret "B_I" or "C_I", or likewise B_I and C_I. Because of this complexity, I wanted to know...

Question

Is there a way in perl to pass in the name of an array index?

Upvotes: 3

Views: 298

Answers (1)

Tanktalus
Tanktalus

Reputation: 22294

Those aren't arrays, those are hashes (dictionaries, associative arrays in other languages). With that, the B_I and C_I are then treated as bareword strings. If these were actual arrays, then these would be treated as bareword function calls, and you'd have to have those available to be called in the caller, and no need for quoting there.

Since you're using hashes, the keys are strings, and you passing in 'B_I' will result in $index being a string of B_I, and since your {$index} has something that isn't allowed in a bareword string (the $), perl will interpret it as a variable instead of a literal, and everything will work exactly the way you want.

Upvotes: 4

Related Questions