Palace Chan
Palace Chan

Reputation: 9183

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

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?

Upvotes: 6

Views: 287

Answers (1)

ephemient
ephemient

Reputation: 204688

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 +.

Upvotes: 11

Related Questions