in reply to head of list + rest of list

Perl allows many ways, depending on whether you want Haskell-style list partition, or imperative list manipulation:

# Haskell programmer: my ($head,@tail) = @list; # Shell programmer my ($head) = shift @list; my @tail = @list; # Perlfunc Author ($head) = splice @list, 0, 1; @tail = @list;

Put $head in list context for the splice example

Replies are listed 'Best First'.
Re^2: head of list + rest of list
by merlyn (Sage) on May 18, 2005 at 18:07 UTC
    You left out "C programmer":
    /\* how are we supposed to declare the size of variables again? */; my $head; /\* scalar (could be number OR string) */; my @tail; /\* array of scalars (could be numbers or strings, and grows + dynamically) */; $head = $list[0]; /\* why isn't this @list[0] ? */; for (my $i = 1; $i <= $#list; $i++) { $tail[$i - 1] = $list[$i]; }

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re^2: head of list + rest of list
by mrborisguy (Hermit) on May 18, 2005 at 18:25 UTC
    ...and Java Programmer:
    Package ArraySeperator; sub new { my ( $class, @rest ) = @_; my $self = [@rest]; bless $self, $class; return $self; } sub head { my $self = shift; return $self->[0]; } sub rest { my $self = shift; my $size = scalar @$self; return @$self->[ 1 .. $size ]; } Package main; my $head; my @rest; my $seperator = ArraySeperator->new( @list ); $head = $seperator->head(); @rest = $seperator->rest();
    Update:
    merlyn, that is not part of the joke. You just have too good of an eye, I guess! It's fixed now. Thanks!
      s/Package/package/ :)
Re^2: head of list + rest of list
by ikegami (Patriarch) on May 18, 2005 at 18:46 UTC

    shift and splice don't work on lists.

    These only work on arrays:

    # Haskell programmer: my ($head, @tail) = @array; # Shell programmer my $head = shift @array; my @tail = @array; # Perlfunc Author my $head = splice @array, 0, 1; my @tail = @array;

    These work on lists (including arrays):

    # Haskell programmer: my ($head, @tail) = list; # Shell programmer my @tail = list; my $head = shift @tail; # Perlfunc Author my @tail = list; my $head = splice @tail, 0, 1;

    By the way, there's no need to put $head in list context for this splice.