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

Hi Monks,
I have this line of code, got it from here, and I just need to know what is happening there.
Can some one explain this line of code for me?
Thanks

my $p_str = join ',', ('?') x @array;

Replies are listed 'Best First'.
Re: Code Explanation
by chromatic (Archbishop) on Jan 03, 2005 at 21:42 UTC

    The repetition operator x, being in list context, creates a list of as many question marks as there are items in @array. join joins them with commas.

    This line of code creates a placeholder string for a SQL statement sent to the DBI. It has to have one question mark in the statement for each parameter -- and @array contains them.

Re: Code Explanation
by Sandy (Curate) on Jan 03, 2005 at 21:52 UTC
    join takes two parameters, the 1st being a deliminator, and the next is a list of items to be joined together, using the deliminator as the glue

    So...

    @array = qw(one two three); $p_str=join ",",@array;
    would set $p_str to one,two,three

    But, your sample code has an extra little something... the list of items is ('?')x@array.

    The x after a string ('?' in this case) is an operator that says, repeat this string x number of times, where x is the number following it.

    So what is x? It is @array, and since this is in scalar context (Perl knows that it is supposed to supply a number not a list), @array returns the number of elements within the array.

    so...

    @array = qw(one two three); $p_str = '?'x@array;
    sets $p_str to '???'

    Finally,

    @array = qw(one two three); $p_str = join ",",'?'x@array;
    is equivalent to...
    @array = qw(one two three); $p_str = join ",","???";
    which simply joins the items ??? (note that there is only one item) together with commas.

    Since there is only one item, there is no comma, and the final result is:

    ???
      A minor correction...
      @array = qw(one two three); $p_str = join ',',('?')x@array; ## parens added here puts the '?'s int +o list format
      The join will return the '?' seperated by commas. "?,?,?"
      In the post that you took this from, the '?'s are used as placeholders
      $p_str = join ",",'?'x@array;

      Sandy's explanation is almost correct. The problem is that in the OP, there are parentheses around the '?' string. Those parentheses matter, because they cause the x operator to act on a list instead of a scalar. So actually, it's more like

      my @array = qw(a b c); my @tmp = ('?') x @array; # @tmp now contains ('?', '?', '?') my $p_str = join ",", @tmp; # $p_str now contains '?,?,?'
Re: Code Explanation
by Fletch (Bishop) on Jan 03, 2005 at 21:41 UTC

    It does the same thing my_str = ( [ '?' ] * array.size ).join( "," ) does in Ruby.

    See also perldoc -f join, and perldoc perlop for the x operator in list context.