in reply to What's happening in this expression?

perl -e 'sub foo {return (1,2,3,4)}; my $a, $x, $y, $z = foo(); print qq{$a, $x, $y, $z\n}'
, , , 4
perl -e 'sub foo {return (1,2,3,4)}; my ($a, $x, $y, $z) = foo(); print qq{$a, $x, $y, $z\n}'
1, 2, 3, 4
  • Comment on Re: What's happening in this expression?

Replies are listed 'Best First'.
Re^2: What's happening in this expression?
by haukex (Bishop) on Oct 11, 2020 at 10:17 UTC
    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.

      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