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

Is there a way, without using for or foreach to assign the contents of an array to a scalar?

I have an array of single letters I want to put back into a word by simply: my $word = @letters; . What's the easiest way to do this?

Replies are listed 'Best First'.
Re: Assigning an array to a scalar
by Arunbear (Prior) on Sep 24, 2004 at 21:09 UTC
    Use the join function: my $word = join('', @letters);
Re: Assigning an array to a scalar
by ikegami (Patriarch) on Sep 24, 2004 at 21:10 UTC

    my $word = join('', @letters);
    and
    my $word = reverse(reverse(@letters));
    and
    my $word = do { local $"=''; "@letters" };
    and
    my $word; map { $word .= $_ } @letters;

    ok, so the last one is pretty much the same as:
    my $word; $word .= $_ foreach (@letters);

Re: Assigning an array to a scalar
by Zaxo (Archbishop) on Sep 24, 2004 at 21:09 UTC

    Many ways. You probably want, my $word = join '', @letters;

    After Compline,
    Zaxo

Re: Assigning an array to a scalar
by hostyle (Scribe) on Sep 25, 2004 at 18:16 UTC
    My poor effort. Seeing as map was already used I went for while / shift.
    while ($_ = shift @letters) { $word .= $_; }
    I thought shift should return the array element, so why do I need to use $_ = shift ... ?
      I thought shift should return the array element, so why do I need to use $_ = shift ... ?
      Because the implied $_ = in a while condition only happens for readline aka <>.

      Also, with shift you don't get the implied defined() around the while condition; if one if the elements of @letters is "0", the loop will stop early. Try while (defined($_ = shift @letters))