Why do we need parentheses in the next perl single insert?

I saw perl one liner to create some random 8 character string:

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

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

+6
source share
1 answer

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

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

Cause

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

doesn't work because it analyzes how

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

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

+11
source

Source: https://habr.com/ru/post/924324/


All Articles