Home > Back-end >  Get the first item of the list returned by function
Get the first item of the list returned by function

Time:01-28

A simple simulation of the problem:

use strict;
use warnings;

sub uniq
{
  my %seen;
  grep !$seen{$_}  , @_;
}

my @a = (1, 2, 3, 1, 2);

print shift @{uniq(@a)}; 

Can't use string ("3") as an ARRAY ref while "strict refs" in use

CodePudding user response:

Need to impose a list context on the function call, and then pick the first element from the list.

The print, or any other subroutine call, already supplies a list context. Then one way to extract an element from a list

print  ( func(@ary) )[0];

This disregards the rest of the list.

That is necessary (try without it), unless we use another set of parens, that is

print( (func(@ary))[0] );

CodePudding user response:

One option could be to return an array reference:

sub uniq {
  my %seen;
  [grep !$seen{$_}  , @_];
}

CodePudding user response:

If uniq returned an array reference, then @{uniq(...)} would be the correct idiom to get an array (which is a suitable argument for shift). For a more general list, you can cast the list to an array reference and then dereference it.

print shift @{ [ uniq(@a) ] };
  •  Tags:  
  • perl
  • Related