Push to array reference

后端 未结 4 482
野的像风
野的像风 2020-12-29 02:40

Is it possible to push to an array reference in Perl? Googling has suggested I deference the array first, but this doesn\'t really work. It pushes to the defere

相关标签:
4条回答
  • 2020-12-29 03:09

    You can push directly onto an array ref without deferencing.

    my $arrayRef = [];
    push $arrayRef, "one";
    push $arrayRef, "two";
    print @$arrayRef;
    

    Outputs

    onetwo
    

    Documentation: http://perldoc.perl.org/functions/push.html

    Starting with Perl 5.14, push can take a scalar EXPR, which must hold a reference to an unblessed array.

    Pre 5.14 you must dereference the array ref first.

    push @$arrayRef, "item";
    

    Edit: Annnnd pushing directly to array ref has been deprecated in a recent perl release (5.24?). Given this, it would be safer to always dereference @{$arrayRef} before pushing to increase the compatibility of your code.

    0 讨论(0)
  • 2020-12-29 03:24

    It might help to think in terms of memory addresses instead of variable names.

    my @a = ();       # Set aside memory address 123 for a list.
    
    my $a_ref = [@a]; # Square brackets set aside memory address 456.
                      # @a COPIES the stuff from address 123 to 456.
    
    push(@$a_ref,"hello"); # Push a string into address 456.
    
    print $a[0]; # Print address 123.
    

    The string went into a different memory location.

    Instead, point the $a_ref variable to the memory location of list @a. push affects memory location 123. Since @a also refers to memory location 123, its value also changes.

    my $a_ref = \@a;       # Point $a_ref to address 123. 
    push(@$a_ref,"hello"); # Push a string into address 123.
    print $a[0];           # Print address 123.
    
    0 讨论(0)
  • 2020-12-29 03:25

    Yes its possible. This works for me.

    my @a = (); 
    my $aref = \@a; # creates a reference to the array a
    
    push(@$aref, "somevalue"); # dereference $aref and push somevalue in it
    
    print $a[0]; # print the just pushed value, again @$aref[0] should also work
    

    As has been mentioned, $aref = [@a] will copy and not create reference to a

    0 讨论(0)
  • 2020-12-29 03:27

    $a is not $a_ref, ($a is the first comparison variable given to a sort{}, and $a[0] is the 0th element of the @a array).Never use $a, or $b outside of a custom sort subroutine, and the @a and @b array should probably be avoided to too (there are plenty of better choices)...

    What you're doing is assigning to $a_ref, an anonymous array, and then pushing onto it "hello", but printing out the first element of the @a array.

    0 讨论(0)
提交回复
热议问题