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

Hi, I am new to perl and need a help with assigning $_ variable to a array within a foreach loop.when i try this following code foreach(@word){ @wordlwr = lc($_); } it only has the last value. any help?

Replies are listed 'Best First'.
Re: need help with array
by jbrugger (Parson) on Jul 18, 2005 at 07:54 UTC
    push @wordlwr, lc($_);
    "We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.
Re: need help with array
by eyepopslikeamosquito (Archbishop) on Jul 18, 2005 at 08:11 UTC

    Or:

    my @wordlwr = map { lc($_) } @word;

        or one character less:

        my @wordlwr = map lc, @word;

        since map can take an expression or a block as it's first argument... now i'll take a bow for the lamest golf ever...
Re: need help with array
by AReed (Pilgrim) on Jul 18, 2005 at 13:37 UTC
    The foreach loop aliases each element of the array to a loop variable for each iteration. If you don't include a loop variable explicitly, perl uses $_ by default.

    The problem with your original code is that each iteration of the loop replaces the contents of your @wordlwr array with the current contents of $_ instead of appending $_ to the array as you expect. I think that the following code is what you want.

    use strict; my @words = qw/ONE TWO THREE/; my @wordlwr = (); foreach (@words) { push @wordlwr, lc($_); } foreach (@wordlwr) { print "$_\n"; }
Re: need help with array
by ghenry (Vicar) on Jul 18, 2005 at 08:53 UTC

    Using foreach in simple terms using simple language, in case you don't understand the above:

    use warnings; use strict; my @word = qw/ ONE TWO THREE FOUR/; foreach my $lcword (@word) { $lcword = lc($lcword); } print "@word";

    HTH.

    Walking the road to enlightenment... I found a penguin and a camel on the way.....
    Fancy a yourname@perl.me.uk? Just ask!!!
      Your code does not use a second array as it is the question of the OP. And it does use the aliasing mechanism of the foreach loop. Maybe you should have mentioned that? I mean, it confuses me from time to time. How is it for a newbie?


      holli, /regexed monk/