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

Hi Monks!

I was wondering how to overwrite values of arrays?
for example if i have an array
@array= qw(A R N D);
and i want to replace those values with 'B N M C'
but as you would with a string like
my @array= qw (A R N D); @array= 'B N M C';
any suggestions?

thanks!

Replies are listed 'Best First'.
Re: replace/ overwrite values of arrays!
by choroba (Cardinal) on May 12, 2014 at 10:00 UTC
    It's so simple I fear I didn't fully understand your question:
    @array = qw(B N M C);
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: replace/ overwrite values of arrays!
by davido (Cardinal) on May 12, 2014 at 14:06 UTC

    my @array = qw( A R N D ); @array = split /\s+/, 'B N M C';

    It seems like you were just missing the split step.


    Dave

      split ' ' would be better (and be just like qw)
Re: replace/ overwrite values of arrays!
by leslie (Pilgrim) on May 12, 2014 at 10:17 UTC

    Hi,

    You can use splice also to achieve this.

    my @array= qw(A R N D); splice(@array,0,4,qw(B N M C));
Re: replace/ overwrite values of arrays!
by Anonymous Monk on May 12, 2014 at 10:01 UTC
Re: replace/ overwrite values of arrays!
by AnomalousMonk (Archbishop) on May 12, 2014 at 11:20 UTC

    I, too, may not really understand your question, but:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @array = qw(A R N D); dd \@array; ;; @array = 'B N M C' =~ m{ \S }xmsg; dd \@array; ;; @array = 'Be No More Care' =~ m{ \S }xmsg; dd \@array; ;; @array = 'Be No More Care' =~ m{ [[:upper:]] }xmsg; dd \@array; ;; @array = 'Be No More Care' =~ m{ \S+ }xmsg; dd \@array; " ["A", "R", "N", "D"] ["B", "N", "M", "C"] ["B", "e", "N", "o", "M", "o", "r", "e", "C", "a", "r", "e"] ["B", "N", "M", "C"] ["Be", "No", "More", "Care"]

    Note that the pattern you use is really important!

Re: replace/ overwrite values of arrays!
by InfiniteSilence (Curate) on May 12, 2014 at 14:00 UTC

    The previous answers were pretty good but in case you are still confused here you go:

    my @array = qw(A R N D); # is equivalent to my @array = (); $array[0] = 'A'; $array[1] = 'R'; $array[2] = 'N'; $array[3] = 'D';

    So it should be obvious to you how you can overwrite any part of the array...simply reference it by its index:

    $array[0] = 'B';

    Celebrate Intellectual Diversity