Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl script to get the first element of arrays passed as reference

Tags:

arrays

perl

I want to call a subroutine by passing around 4 arrays to it and then get the first value of each array and then create a new array(array of first elements of arrays that are passed) in the subroutine and then return back that array. Here is the code I tried with

my @a = (97,34,6,7);
my @b = ("A", "B", "F", "D");
my @c = (5..15);
my @d = (1..10);
my @tailings = popmany ( \@a, \@b, \@c, \@d );

print @tailings;

sub popmany {
    my @retlist = ();
    for my $aref (@_) {            #1
        my $arrele = @$aref;       #2
        push @retlist , $arrele    #3
    }
    return @retlist;
}

Here in #1 I use a loop and get the first array , then in line 2 I assign the whole array to a variable, thinking that by default the perl will only store the first variable of array into @arrele. the I push the $arrele to a new array @retlist , Sorry I dint refer any notes, so my procedure might be wrong. But this is throwing me a output like 441110

which has no sense.

Please explain me the code how can I do that.

like image 816
mac Avatar asked Dec 02 '22 00:12

mac


1 Answers

It's here:

my $arrele = @$aref;

where you're asking perl to put @{$aref} into scalar context, which returns the length (number of elements in) the array pointed at by $aref.

Instead try:

my $arrele = $aref->[0];

which will access the first element of the array instead.

like image 149
Alex Avatar answered Jun 13 '23 13:06

Alex