P09 - Pack consecutive duplicates of list elements into sublists.

Author: Rob Eaglestone

Specification

P09 (**) Pack consecutive duplicates of list elements into sublists.
    If a list contains repeated elements they should be placed in separate
    sublists.

Example

> pack_dup().perl.say
[["a","a","a","a"],["b"],["c","c"],["a","a"],["d"],["e","e","e","e"]]

Source code: P09-rje.pl

use v6;

# Robert Eaglestone  22 sept 09
#
#   My first Perl6 script - I'm sure this can be done better
#
my @in = ;
my @out = pack_dup( @in );
@out.perl.say;

sub pack_dup(@in) {
    my @out = [ [@in.shift], ];

    for @in -> $elem {
        push @out, [] if $elem ne @out[*-1][0];
        push @out[*-1], $elem;
    }
    return @out;
}