newbie needs help [references and values]

Discussion in 'Perl Misc' started by John, Sep 30, 2003.

  1. John

    John Guest

    Dear listers,

    I have just started on perl and I have a question about if the thing I
    copy is copy the value itself or I am copying the refence.

    Can you help me with that?

    The code is writen below.

    My question is if I (as I understand) copy the values of @a into @b
    and then I change the values for @a (on the subroutines) and print
    then back. Why @b is altered?

    If this is the normal behavior,

    Why $st1 and $st2 do look to have the same behavior?

    What I am missing?

    Thanks for your advise.

    #the code################################

    use strict;

    my $st1="abcdefabcdef";

    my @a = ( [qw(1 2 3 4 5 6)],
    [qw(2 4 6 8 10 12)],
    [qw(3 5 7 9 13 15)]

    my @b = @a;

    print $a[1][2],"\n"; # before to do anything PRINT 6
    print $a[1][3],"\n"; # before to do anything PRINT 8

    pe(\@a); # call the module

    print $a[1][2],"\n"; # this value has changed PRINT 88
    print $a[1][3],"\n"; # this has changed too PRINT 55
    print $b[1][3],"\n"; # but why this has changed is is reffered to
    # another array??? WHY PRINT 55?????
    # if this is the normal behavior... read down

    print "\n";

    my $st2= $st1;

    $st2 =~ tr/abcdef/123456/;

    print "$st1\n"; # why in this case we change one and the
    print "$st2\n"; # other remains as it was?

    sub pe{
    my ($inner1)= @_;


    sub per{
    my ($inner2)[email protected]_;


    and the result is:

    John, Sep 30, 2003
    1. Advertisements

  2. Note that @a is an array of references to arrays of numbers.
    When doing "@b = @a", you copy the references to those arrays
    over to @b.

    That should answer most of your questions.

    Andreas Kahari, Sep 30, 2003
    1. Advertisements

  3. John

    Anno Siegel Guest

    You mean "seem to have a different behavior".
    The elements of @a are array references.
    Here you copy the references from array @a to @b. The actual (anonymous)
    arrays the references are pointing to are the same for both @a and @b.
    So, if you change one (through @a below), the other changes too.
    You mean "call the routine". There is no module involved.

    Using a subroutine to make changes to @a is just obfuscation. It would
    have been clearer to put the code right here:

    $a[1]->[2] = 88;
    $a[1]->[3] = 55;
    Because both $a[1] and $b[1] point to the same anonymous array, which
    you have changed.
    Here no references are involved. $st1 and $st2 point to two different


    Anno Siegel, Sep 30, 2003
  4. Glenn Jackman, Sep 30, 2003
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.