in reply to Trying to slice off all array elements but the last one

Just for grins I whipped up the following code:

use Data::Dumper; use strict; my @foo=qw / a b c d e f / ; printf "Before:\n"; print Dumper(\@foo); $#foo--; printf "After:\n"; print Dumper(\@foo);

When run it produced:

Before: $VAR1 = [ 'a', 'b', 'c', 'd', 'e', 'f' ]; After: $VAR1 = [ 'a', 'b', 'c', 'd', 'e' ];
The key here is the decrement of $#foo which reduces the maximum index value for the array @foo. IIRC the element you are disassocating will be reaped in memory eventually.


Peter L. Berghold -- Unix Professional
Peter at Berghold dot Net
   Dog trainer, dog agility exhibitor, brewer of fine Belgian style ales. Happiness is a warm, tired, contented dog curled up at your side and a good Belgian ale in your chalice.

Replies are listed 'Best First'.
Re: Re: Trying to slice off all array elements but the last one
by dragonchild (Archbishop) on Feb 16, 2004 at 21:12 UTC
    It's also not what the OP wanted. The idea was to slice the array non-destructively Messing with $#foo is also very mean to your maintainer(s). It's the very definition of action-at-a-distance. In other words, Don't do this unless you know exactly why you shouldn't.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: Re: Trying to slice off all array elements but the last one
by Art_XIV (Hermit) on Feb 16, 2004 at 21:07 UTC

    I found $#foo-- to be both clever and scary at the same time. :)

    Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"
Re: Re: Trying to slice off all array elements but the last one
by CountZero (Bishop) on Feb 17, 2004 at 06:54 UTC
    IIRC the element you are disassocating will be reaped in memory eventually.
    The Camel Book says it doesn't get reaped (p. 76):
    Truncating an array does not recover its memory. You have to undef($whatever) to free its memory back to your process's memory pool.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law