Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to list

Tags:

perl

sub get_list {
    return ("one", "two");
}

sub get_array {
    my @a = ("one", "two");

    # need to convert @a to list
    return @a;
}

my $two = get_list(); # desired, assigns last item in list to scalar 
my $count = get_array(); # evaluates array in scalar context, returning a count

In the get_array() method, I already have an array created, but I want to return it as a list so that it assigns according to list rules and not array rules. The array of course would normally be built in a more complex way (not directly from a list).

I have tried using map in hopes that it would return me a list of values, but this gives the same results. Same with split/join.

return map { $_ } @a;
return split /,/, join(",", @a);

How can I convert the array into a list of values?

like image 484
Despertar Avatar asked Sep 21 '26 09:09

Despertar


1 Answers

Functions can use wantarray to determine the context they're in and return something accordingly:

sub get_array {
    my @a = ("one", "two");
    return wantarray ? @a : $a[-1];
}
like image 180
Sean Avatar answered Sep 24 '26 01:09

Sean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!