Use of "shift" in Functions

Contents | Up | Prev | Next

# 4.2. Use of "shift" in Functions

One can use the `shift` function to extract arguments out of the argument array. Since this use is so common, then simply typing `shift` without any arguments will do exactly that.

Here is the split program from the previous slide, which was re-written using `shift`:

    sub mysplit
    {
        my $total = shift;
        my $num_elems = shift;
        my @accum = @_;
        my (@ret, @new_accum);

        if ($num_elems == 1)
        {
            push @accum, $total;
            print join(",", @accum), "\n";

            return;
        }

        for(my $a=0;$a<$total;$a++)
        {
            @new_accum = (@accum, $a);
            mysplit($total-$a, $num_elems-1, @new_accum);
        }
    }

    mysplit(10,3);

Contents | Up | Prev | Next