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

I would like to write a function makelist($x,$n), which returns a list of $n elements, each element being the scalar $x. A pretty naive implementation looks like this:

sub makelist { my ($elem,$count)=@_; my @list; $list[$count-1]=0; map { $elem } @list }
However I wonder if there is a more concise way of doing this, maybe one where I don't need a temporary @list. If it would be a string of $n occurances of $x, I would simply write $x x $n. Can I do something similarily simple for lists?

-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re: generating a list of identical elements
by jethro (Monsignor) on Jan 19, 2011 at 11:33 UTC

    You can do this with the x operator as well:

    perl -e '$x="ab"; $n= 20; @f= ($x) x $n; print join "|",@f;' #prints ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab|ab

      Great!!! I had not expected this possibility, so I did not look up the definition of this operator. My fault, and thank you for telling me!

      -- 
      Ronald Fischer <ynnor@mm.st>

        In Perl, the slogan could be "There's an op for that." ...but someone would probably get sued...

        --Ray

Re: generating a list of identical elements
by JavaFan (Canon) on Jan 19, 2011 at 11:41 UTC
    If it would be a string of $n occurances of $x, I would simply write $x x $n. Can I do something similarily simple for lists?
    @list = ($elem) x $count;
Re: generating a list of identical elements
by tilly (Archbishop) on Jan 19, 2011 at 16:53 UTC
    If you want to use the map version:
    sub makelist { my ($elem, $count) = @_; map $elem, 1..$count; }
Re: generating a list of identical elements
by fisher (Priest) on Jan 19, 2011 at 11:29 UTC
    I suppose using push function will be a better solution? I mean, like this:
    sub makelist { my @list; for (1..$_[1]) { push @list, $_[0] }; return @list; }