Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first item of the list returned by function

Tags:

perl

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

like image 415
Ωmega Avatar asked Sep 14 '25 05:09

Ωmega


1 Answers

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 returned list

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

This disregards the rest of the list.

That + is necessary (try without it), unless we equip print itself with parentheses around all its arguments, that is

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

See this and/or this for examples and docs about the need for that + or ().

like image 197
zdim Avatar answered Sep 17 '25 07:09

zdim