Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: What's happening in this expression?

by haukex (Archbishop)
on Oct 11, 2020 at 10:17 UTC ( [id://11122697]=note: print w/replies, xml ) Need Help??


in reply to Re: What's happening in this expression?
in thread What's happening in this expression?

return (1,2,3,4)

Protip: Don't use numbers like this to debug lists and arrays, because it makes it impossible to tell the difference between a list returning its last value and an array returning its size.

Replies are listed 'Best First'.
Re^3: What's happening in this expression? (Pro Tip: never return range)
by LanX (Saint) on Oct 12, 2020 at 19:13 UTC
    Yes, that's why I always use characters ... but there is another trap lurking ...

    Extra tip: never use the range operator to return a list.

    One of the most annoying design flaws of Perl is the propagation of context to a subs returning statement. That's action at a distance...

    And you really don't want a flip-flop when you expect a list...

    DB<50> sub tst { "a".."d" } DB<51> x tst() # list context => range 0 'a' 1 'b' 2 'c' 3 'd' DB<52> p scalar tst() # scalar context => flip-flop 1E0 DB<53> x tst() # list context => WTF??? 0 0 DB<54> x tst() # once flip-flop, always flip-flop 0 0 DB<55>

    Workaround: reverse

    DB<44> sub tst { reverse "a".."d" } DB<45> x tst() 0 'd' 1 'c' 2 'b' 3 'a' DB<46> p scalar tst() dcba DB<47> x tst() 0 'd' 1 'c' 2 'b' 3 'a' DB<48>

    And if don't like the order, reverse twice

    DB<55> sub tst { reverse reverse "a".."d" }

    update

    another - uglier - alternative:

    DB<59> sub tst { @{["a".."d"]} } DB<60> x tst() 0 'a' 1 'b' 2 'c' 3 'd' DB<61> p scalar tst() 4 DB<62> x tst() 0 'a' 1 'b' 2 'c' 3 'd' DB<63>

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11122697]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (1)
As of 2024-04-25 04:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found