I've been using the implementation of uniq shown here for a couple of years in various scripts, and I just realized I don't understand how it's returning an array.
That implementation is as follows:
sub uniq {
my %seen;
grep !$seen{$_}++, @_;
}
my @array = qw(one two three two three);
my @filtered = uniq(@array);
Can someone explain how that two line sub is returning an array that gets assigned to @filtered
? I.e. why do we not need to take some result from the grep line and return it?
Looking at the sub itself in isolation, my assumption would have been that the grep line was operating on an array passed by reference, @_
, and that the calling line could just be uniq(@array);
, with @array
being modified after that call.
This is purely for my own understanding, I've got no beef with the functionality of this sub, which I've been using with great success.