5 ms·
So let's break it down: sub It's an anonymous sub (@) It has a prototype that says it accepts a list of arguments (this is the default in perl thoug
by falsedan 9y ago
So let's break it down:
sub
It's an anonymous sub
(@)
It has a prototype that says it accepts a list of arguments (this is the default in perl though).
Prototypes are mostly for giving hints to the compiler on how to unambiguously parse calls to your function later. For an anonymous sub, it's pointless because you assign its value to a variable, and then brackets are required when calling it.
return
It returns the result of the map (this default in perl is to return the result of the last expression & everything is an expression though)
map
same as python map(code, list)
{ "@{[ <some stuff> ]}" }
This is a particular perl goof for interpolating array lookups into a string. Usually, perl's sigils let variables be interpolated without any issue, but since we're using $_[0] to use the first element of the @_ array, it's ambiguous with $_ . '[0]'.
The @{} dereferences the contents of the braces as an array, and [] creates a new arrayref. The arrayref has one element, and perl's default stringification of an array (join them all with no separator) means that it… iterpolates the thing inside the @{[]} into the surrounding string.
This is pointless though, since it's the only thing in the string. The author might have been trying to give a string context to force stringification of the thing, but the dot operator already provides that context.
$_[0] . $_
This is a string of the first element of … hmm. Not of the currently-mapped element (that's $_). $_[0] refers to the first element of @_. This makes a new value which is the concatenation of the first element with the current element.
@$_
This is a short way of writing @{ $_ }: dereference the arrayref that's stored in $_. But $_ is not set anywhere, so I assume this is a typo of @_
I would have written this as:
my $prefixer = sub { my($prefix , @rest) = @_; return map { $prefix.$_ } @_ };
And it would work like this:
say $prefixer->('Hi_', 1, 'str', 7);
> 'Hi_Hi_Hi_1Hi_strHi_7'
The 'best' way to write it would have been:
sub { $_[0].join($_[0], @_) }
- falsedan 9y agoThe python equivalent is lambda *lst: ''.join([str(lst[0]), str(lst[0]).join([str(_) for _ in lst])]) Which is uh… begging for an initial line of "lst = map(str, lst)"
- AlexCoventry 9y agoWow, that was a journey. Thanks.
- falsedan 9y agoA more idiomatic solution: lambda *lst: ''.join(['{}{}'.format(lst[0], _) for _ in lst])
- RodgerTheGreat 9y agoIf I follow correctly, the equivalent in K would be {,/(*t),/:t:$x} Flatten (,/) the first element of the list (*t) joined with each element of the list (a,/:b), where t is the input x cast to a list of strings (t:$x). Curly braces make the expression an anonymous function, and since no argument names are specified explicitly the name x is the single input argument.