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

In perl, array get and set, hash get and set are value-based. When you set/get a scalar from an array/hash, its value is copied:
my @array; my $i = "abcd"; $array[0] = $i; # $array[0] won't change $i = "efgh"; my %hash; my $i2 = 1234; $hash{'key'} = $i2; # $hash{'key'} won't change $i2 = 5678;
However, in the perl's C interface, calls like av_store, av_fetch, hv_store, hv_fetch, av_push, av_pop, the scalar itself is really being stored to the container, or fetched from the container, instead of its copy. So, if I'm going to make a general-purpose C++ wrapper for perl, should I imitate the behavior of perl, or just follow the behavior of perlapi?

Replies are listed 'Best First'.
Re: The behavior of array and hash OPs
by Anonymous Monk on Jun 22, 2011 at 07:07 UTC
Re: The behavior of array and hash OPs
by 7stud (Deacon) on Jun 22, 2011 at 01:27 UTC
    When you set/get a scalar from an array/hash, its value is copied:
    Not always:
    use strict; use warnings; use 5.010; my @arr = (1, 2, 3); for (@arr) { $_ *= 2; } print "@arr\n"; --output:-- 2 4 6
      Yes, always. Unless you claim you can change the result of the multiplication after you assigned it, and that doing so changes the array.
      How about if I claim that when perl gets the thing from the array, it is not a copy of the value because when I change it, the array changes?
        How about you claim that "the foreach loop index variable is an implicit alias for each item in the list that you're looping over. " as mentioned in the perlsyn section on foreach?
        A reply falls below the community's threshold of quality. You may see it by logging in.
      The array iterator is specially treated. If you use more 'common' way, it is copied by value:
      $ perl -E 'my @array=qw/1 2 3/; my $first=$array[0]; $first=0; say "ar +ray: @array"; say "fetched changed: $first";' array: 1 2 3 fetched changed: 0
Re: The behavior of array and hash OPs
by locked_user sundialsvc4 (Abbot) on Jun 22, 2011 at 15:58 UTC

    The magic is “references,” which are scalars too.

    Perhaps you could elaborate on this “general-purpose wrapper,” and describe in more detail exactly how you intend for it to be used by C++ programmers ...

      Actually, not too "general". I attempt to design and use it as a scripting engine in a game.
      So, the typical usage would be: calling a perl sub with wrapped game object as argument.