No such thing as a small change | |
PerlMonks |
Forcing list context. Brackets (with list within) as an unary right-associative operatorby rsFalse (Chaplain) |
on Mar 01, 2019 at 13:00 UTC ( [id://1230712]=perlquestion: print w/replies, xml ) | Need Help?? |
rsFalse has asked for the wisdom of the Perl Monks concerning the following question:
Hello, Here I'll write a collection of ways how to force list context, and next I will write some examples of using construction '( LIST )[ LIST ]', where brackets used as unary right-associative list-context forcing operator. Some links, which are (or can be) related to this topic: ! Context tutorial use of parentheses around a variable Scalar Vs. List context If you believe in Lists in Scalar Context, Clap your Hands (Answered) How to force list context? So, e.g., I have a code , 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). Match in scalar context, outputs ':1' (upd1. '1' stays for successful match, i.e. "logical true") List of ways to force a list context: '()=' list assignment operator forces list context. Must be parethessized because '.' precedence is higher than of assignment. perlsecret Babycart op. Referencing + dereferencing. Taking a slice of hash ( %_ ). May be any hash. For viewing how match have run, we can add '/.(?{ print $& })/g'. Asking some list elements (e.g. one element, e.g. which index is '1'). Speed of different methods. I tried these four methods for a string of length 5e5. Both first and second ways consumed 0.33 s, and 3rd and 4th ways consumed 0.25 s. I think this is because: former ways manipulate every element of a list generated by match, and later ways try to access only one element of some structure. Asking for no elements of the list by using something inside "brackets operator". I name brackets as an operator, but I do not know it a true operator? Also, I haven't seen it in perlop operator precedence list. Here are some ways how to ask none of elements: Simply concatenates with uninitialized value which self-stringifies into ''. Same with perl -wle '$_ = "345678"; print ":" . ( /./g )[ {} ]'. 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. And for these two I get strange behavior:
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. Here, if we use some number instead of colon, we can get unexpected behavior (with no warnings): '5' stands for 3rd element, i.e. index = 2.
Back to
Seekers of Perl Wisdom
|
|