"Perl for Perl Newbies" - Part 2FunctionsUse of "shift" in Functions

4.2. Use of "shift" in Functions

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

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

use strict;
use warnings;

sub 
mysplit
{

my
$total =
shift;

my
$num_elems =
shift;

my
@accum =
@_;


if (
$num_elems ==
1)
    {

push
@accum,
$total;

print
join(
",",
@accum),
"
\n
";


return;
    }


for (
my
$item =
0 ;
$item <=
$total ;
$item++)
    {

my
@new_accum = (
@accum,
$item);
        mysplit(
$total-
$item,
$num_elems-
1,
@new_accum);
    }
}

mysplit(
10,
3);

Written by Shlomi Fish