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



Hi.. PERL Monks,

I'm new to this forum, I have a requirement, I want to
square the array values itself, ( without new array)


Example:

my @arr = qw( 1 2 3 4 5 6 7 8);

I need to change the array like the following without new array.

@arr = qw( 1 4 9 16 25 36 49 64);

Thanks in advance...

Replies are listed 'Best First'.
Re: Square the array values.
by GrandFather (Saint) on Mar 18, 2010 at 09:35 UTC

    I'd just:

    my @arr = map {$_ * $_} qw( 1 2 3 4 5 6 7 8);

    or if the array already exists:

    $_ *= $_ for @arr;

    True laziness is hard work
Re: Square the array values.
by chromatic (Archbishop) on Mar 18, 2010 at 09:08 UTC

    Somehow you have to loop through the array and modify the values in place with the exponentiation operator (or the multiplication operator). perlsyn describes most of the interesting parts in the section on "Foreach Loops".

      Is this you are expecting.
      use strict; use warnings; use Data::Dumper; my @array=(1,2,3); print Dumper \@array; my $len=$#array; while($len>=0) { $array[$len]=$array[$len]*$array[$len]; $len--; } print Dumper \@array;


      Or use the following way.
      my @array=(1,2,3); foreach (@array) { $_=$_*$_; }

        The latter is much better, though you could multiply and assign in place with =*:

        for (@array) { $_ *= $_; }

        ... or even use postfix iteration:

        $_ *= $_ for @array;
Re: Square the array values.
by BrowserUk (Patriarch) on Mar 18, 2010 at 10:30 UTC

    For completeness:

    @a = 1..10;; $_ **= 2 for @a;; print @a;; 1 4 9 16 25 36 49 64 81 100

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Thanks to all..
Re: Square the array values.
by Marshall (Canon) on Mar 18, 2010 at 09:15 UTC
    To modify the input array, pass an array reference to the subroutine.
    #!usr/bin/perl -w use strict; my @arr = qw( 1 2 3 4 5 6 7 8); square(\@arr); sub square { my $arrayref = shift; foreach my $item (@$arrayref) { $item **=2; #or #$item *=$item; } } foreach (@arr) { print "$_\n"; } __END__ prints: 1 4 9 16 25 36 49 64
    This will produce the same @arr, but not quite in the same way:
    my @arr = qw( 1 2 3 4 5 6 7 8); foreach (@arr) { $_*=$_; } #or @arr = map($_*$_}@arr;
Re: Square the array values.
by pajout (Curate) on Mar 18, 2010 at 09:39 UTC
    Though it could be considered ugly, map can help you:

    pajout@balvan:~$ perl -e 'my @a = (1,2,3); print join(",", map {$_*$_} + @a)."\n";' 1,4,9