jar00n has asked for the wisdom of the Perl Monks concerning the following question:

I'm fairly new to Perl and my searches for an answer to this question drew thousands of irrelevant matches due to the vagueness of my issue. I was toying with repeating a sequence and Perl appears to be doing arithmetic with the 'x' operator:

#!/usr/bin/perl use strict; use warnings; print "Enter some strings:\n"; my @lines = <>; print 0..9 x 2, "\n"; foreach (@lines) { printf "%20s", $_; }

This produces a header line:

$ ./ex05-02.pl Enter some strings: asdfasdfasdf asdfa asdfasdfasd asdf 0123456789101112131415161718192021222324252627282930313233343536373839 +404142434445464748495051525354555657585960616263646566676869707172737 +475767778798081828384858687888990919293949596979899 asdfasdfasdf asdfa asdfasdfasd asdf

Not 01234567890123456789 as I had expected it to, ultimately I wanted a 20 character header but 0..9 x 2 is being interpreted unexpectedly for me. I would love for anyone to be able to shed some light on why this happening.

Replies are listed 'Best First'.
Re: Seemingly odd behavior of sequence
by oiskuu (Hermit) on Dec 04, 2013 at 11:47 UTC
    The expression 0..9 x 2 evaluates as 0 .. (9 x 2). Put parentheses around the range op:
    print +(0..9) x 2, "\n";
    See perlop for the list of operator precedences. Hmm, or perlop (man page).
    The table appears somewhat mangled on [doc://perlop].
      Thanks for the reply, I figured that was happening in a moment of genius in the shower... "What if the 'x' operator has a higher precedence than the sequence expansion?"
Re: Seemingly odd behavior of sequence
by Kenosis (Priest) on Dec 04, 2013 at 17:27 UTC

    If you're curious how Perl parses an expression--perhaps for debugging purposes or just for the pure joy of it on a rainy afternoon--you can use the module B::Deparse at the command line as follows:

    perl -MO=Deparse,-p -e 'print 0..9 x 2, "\n";'

    Output:

    print((0 .. (9 x 2)), "\n"); -e syntax OK

    Note that the output echoes oiskuu's spot-on assessment of your expression's evaluation.

      And many thanks to you for showing me this debugger.

        You're most welcome, jar00n!