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.
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...
Is there a way in perl to pass in the name of an array index?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With