perl - How to the access the last item of a list returned by a subroutine without copying it into an array first? -
this question has answer here:
i'm looking computationally less expensive way access last item of list returned subroutine (without modifying subroutine itself).
as see i'm doing below copying returned list named array @list, or anonymous array [], , accessing last value of array, not directly last item of returned list.
is there shortcut here? how can directly access last item of returned list?
sub range { return 0 .. 10**7 } this takes 0.808 seconds of user time according gnu time:
my @array = range(); print pop @array; and here 0.792 seconds:
my @array = range(); print $array[$#array], "\n" 0.680 seconds:
print pop [ range() ]
subroutines don't return arrays, return lists. you're correct that
my @array = list(); copies values returned list() array. if care last value, can use list slice:
use strict; use warnings 'all'; use 5.010; sub range { return 0 .. 10**7; } ($last) = ( range() )[-1]; $last; # 10000000
Comments
Post a Comment