Then I have an array and a simple task that trim white spaces:
my @ Ar = ("bla", "ha1") sub trim {my $ a = shift; $ A = ~ s / \ s + $ //; $ A} Now, I want to apply it to an array with map function. Why can not I do this in the name of the function like it is built in functions in one?
e.g. You can
print map (length, @ r) but you can not do
print Map (trim, @r) You have to do this:
print map {trim ($ _)} @ar print map (trim ($ _), @r)
if you are using version 5.10 or later , You specify _ for trim if you are using earlier versions, then use it :
As the last character of a prototype, or before a semicolon, you can use
_$: if If this argument is not provided, instead of$ _will be used.
Use strict; Use warnings; My @ x = ("bla", "ha 1"); Sub trim (_) {my ($ x) = @_; $ X = ~ s! \ S + $ !!; $ X} Print map trim, @x; Incidentally, do not use $ a and $ b one sort outside the comparator: They are immune from the strict investigation.
However, I prefer not to use prototypes for primarily writing functions because their use makes it difficult to mentally parse the code. Therefore, I like to use it:
map trim ($ _), @x; See also:
This is absolutely powerful, and it should be used to make the world a better place.
No comments:
Post a Comment