Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need braces in the following perl one liner?

Tags:

perl

I saw a perl one liner to generate some random string of 8 chars:

perl -le 'print map { ("a".."z")[rand 26] } 1..5'

but this does not work without the {} for map. Why is that?

like image 588
Palace Chan Avatar asked Sep 01 '12 03:09

Palace Chan


1 Answers

See perldoc -f map. map has two forms: map({block} @array) and map(expression, @array). The latter form can be used like so:

perl -le 'print map(("a".."z")[rand 26], 1..5)'
perl -le 'print map +("a".."z")[rand 26], 1..5'

The reason

perl -le 'print map ("a".."z")[rand 26], 1..5'

doesn't work is because it parses like

perl -le 'print(((map("a".."z"))[rand(26)]), 1..5)'

In other words, "a".."z" become the only arguments of map, which is not valid. This can be disambiguated with an extra set of parentheses or with a unary +.

like image 91
ephemient Avatar answered Nov 14 '22 23:11

ephemient