rsFalse has asked for the wisdom of the Perl Monks concerning the following question:
, where XXX is something what I want in LIST context. The concatenation dot '.' forces scalar context. (In this example, '.' changing to ',' would solve a task well). In examples I'll use regex match '/./g' for XXX (upd2. match (m) has different behavior depending on context).perl -wle 'print ":" . XXX'
Match in scalar context, outputs ':1' (upd1. '1' stays for successful match, i.e. "logical true")perl -wle '$_ = "345678"; print ":" . /./g'
'()=' list assignment operator forces list context. Must be parethessized because '.' precedence is higher than of assignment.perl -wle '$_ = "345678"; print ":" . ( () = /./g )' # output: ':6' (6 - number of matches; special behaviour)
perlsecret Babycart op. Referencing + dereferencing.perl -wle '$_ = "345678"; print ":" . @{[ /./g ]}' # output: ':6' (6 - number of matches => number of array elements)
Taking a slice of hash ( %_ ). May be any hash. For viewing how match have run, we can add '/.(?{ print $& })/g'.perl -wle '$_ = "345678"; print ":" . @_{ /./g }' #Use of uninitialized value in concatenation (.) or string at -e line +1. #:
Asking some list elements (e.g. one element, e.g. which index is '1').perl -wle '$_ = "345678"; print ":" . ( /./g )[ 1 ]' # output: ':4' (second match for e.g. index 1)
Both first and second ways consumed 0.33 s, and 3rd and 4th ways consumed 0.25 s.perl -wle '$_ = "3" x 5e5; print ":" . method( XXX )'
Simply concatenates with uninitialized value which self-stringifies into ''. Same with perl -wle '$_ = "345678"; print ":" . ( /./g )[ {} ]'.perl -wle '$_ = "345678"; print ":" . ( /./g )[ [] ]' #Use of uninitialized value in concatenation (.) or string at -e line +1. #:
Uninitialized value inside list (inside-bracket list), which casts to numeric and becomes 0, so first element of a list (target list), i.e. 3, is returned.perl -wle '$_ = "345678"; print ":" . ( /./g )[ undef ]' #Use of uninitialized value in list slice at -e line 1. #:3
perl -wle '$_ = "345678"; print ":" . ( /./g )[()]' #Argument ":" isn't numeric in list slice at -e line 1. #:3
In these two, it seems that a 'colon' is cloned and transported into brackets and evaluated here. It evaluates to numerioc, i.e. 0, and returns first element of a list, i.e. 3.perl -wle '$_ = "345678"; print ":" . ( /./g )[@_]' #Argument ":" isn't numeric in list slice at -e line 1. #:3
'5' stands for 3rd element, i.e. index = 2.perl -wle '$_ = "345678"; print "2" . ( /./g )[()]' #25
perl -wle '$_ = "345678"; print "2" . ( /.(?{ print $& })/g )[()]' 3 4 5 6 7 8 25
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Forcing list context. Brackets (with list within) as an unary right-associative operator
by choroba (Cardinal) on Mar 01, 2019 at 13:31 UTC | |
by haukex (Archbishop) on Mar 01, 2019 at 21:06 UTC | |
by rsFalse (Chaplain) on Mar 01, 2019 at 14:04 UTC |