1

I have something like the following code

my @array = ["hello","hi","fish"];
sub this_sub {
  my $first = $_[0];
  my $second = $_[1];
  my $third = $_[2];
}
this_sub(@array);

How can I make the array expand into an argument list so that first, second and third will get the value from the strings in the array. like below.

  • first = "hello"
  • second = "hi"
  • third = "fish"
2
  • 2
    The truth is that you cannot prevent an array from expanding into an argument list unless you fiddle around with prototypes. Commented Sep 3, 2012 at 13:59
  • WOW! perl's mysub (a, b, c) is LITERALLY the same as mysub @mylist. AMAZING. This is so cool. Commented Nov 30, 2016 at 18:53

2 Answers 2

6

Your code is wrong. To assign a list to an array, enclose it in normal parentheses:

my @array = ("hello", "hi", "fish");

Square brackets define an anonymous array, i.e. a referenco to a list, which is a scalar:

my $array_ref = ["hello", "hi", "fish"];

If you want to send a reference, you have to dereference it in the sub:

sub this_sub {
    my ($first, $second, $third) = @{ $_[0] };
}
Sign up to request clarification or add additional context in comments.

1 Comment

That is very helpfull I will try it out and be back soon!
1

It is sometimes beneficial to be able to expand the array into an argument list since one usually do not have access to the subroutine in question. Here's my solution.

sub test_sub($$$) {
    my ($a,$b,$c) = @_;
    say "$a $b $c";
}
my @array = ('happy', 'birthday', 'to you');
my $eval_str = 'test_sub(' join ', ', @array . ')';
eval $eval_str;

It is somewhat ugly, hopefully someone else can suggest an improved version.

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.