in reply to Non-destructive array processing

Isn't this what local is for? Something like the following;

my @array = 1..10; { local @array = @array; while (my @chunk = splice @array, 0, 2) { print "Chunk: @chunk\n"; } } print "Original array is still intact! (@array)\n";

Replies are listed 'Best First'.
Re^2: Non-destructive array processing
by Aristotle (Chancellor) on Jan 22, 2003 at 16:09 UTC
    Nearly.
    local *array = \@array;
    This will work with lexically scoped variables too.

    Makeshifts last the longest.

      But what will simply alias the lexical @array with the dynamical @array. So I don't see what you've achieved by doing this.

      One problem with this that you probably didn't foresee is that lexicals are resolved before dynamic variables. Example:

      my @foo = 1..4; local *foo = ['a'..'d']; print @foo; # 1234
      The problem is solved through our() since that creates an aliased lexical:
      my @foo = 1..4; our @foo = 'a'..'d'; print @foo; # abcd

      ihb
Re: Re: Non-destructive array processing
by jdporter (Paladin) on Jan 21, 2003 at 22:24 UTC
    Nope, because local() doesn't work on my variables. Nice thought, though.

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.

Re: Re: Non-destructive array processing
by ihb (Deacon) on Jan 22, 2003 at 19:01 UTC
    No, but you can use my:
    my @array = 1..10; { my @array = @array; while (my @chunk = splice @array, 0, 2) { print "Chunk: @chunk\n"; } } print "Original array is still intact! (@array)\n";
    Note though that modifications of an @array element (i.e. via $array[$n]) will disappear when the scope is left. This is simply because the inner @array simply is another variable with the values copied. The idea of Juerd's routine was that the elements would be aliased but the array different.

    Hope I've helped,
    ihb