in reply to Re^7: chopping a string into slices - is there a more elegant way to do it?
in thread chopping a string into slices - is there a more elegant way to do it?

I've just been tripped up by:

  my @foo = (2, 3,  4  x 17, 3, 2, 0, 0)

being quite different from:

  my @foo = (2, 3, (4) x 17, 3, 2, 0, 0)

which looks as if the '()' confer some quality of list-ness. The documentation says:

.... In scalar context or if the left operand is not enclosed in parentheses, it returns a string consisting of the left operand repeated the number of times specified by the right operand. In list context, if the left operand is enclosed in parentheses or is a list formed by qw/STRING/, it repeats the list.

so the brackets are part of the syntax... I confess that I was (for reasons unknown) expecting 'x' to do listy things in List Context and scalary things otherwise. (Many things take lists of arguments, so I guess it would be inconvenient for (e.g.) '-' x 24 to yield a list in List Context.)

Similarly, of course,  foreach VAR(LIST) BLOCK reenforces the feeling that '()' have something to do with the making of lists.

Replies are listed 'Best First'.
Re^9: chopping a string into slices - is there a more elegant way to do it?
by ikegami (Patriarch) on Dec 02, 2008 at 05:29 UTC

    I confess that I was (for reasons unknown) expecting 'x' to do listy things in List Context and scalary things otherwise

    I recall the developers of Perl a bit ashamed of that one. I don't know if it was done that way for backwards compatibility or if it was simply a case of the consequences not being anticipated. It really does break the mold.

    Similarly, of course, foreach VAR (LIST) BLOCK reenforces the feeling that '()' have something to do with the making of lists.

    Really?

    for (foo()) { bar() } # List while (foo()) { bar() } # Scalar if (foo()) { bar() } # Scalar print(foo()) # List length(foo()) # Scalar

    I even use for as a topicalizer regularly.

    for ($var) { # Scalar s/^/[/; s/$/]/; }

    The purpose of parens in flow control statements in Perl5 is purely decorative. However, their roots are in C, where their purpose is for precedence.