views:

121

answers:

2

I'm trying to write the following recursive function. The problem is that it never ends and I can't understand why:

    sub do_smth(@first, @second){
    my @tmp_first = @first;
    $tmp = shift(@tmp_first);
    if (@tmp_first > 0){
        do_smth(@tmp_first, @second);
    }
    my @tmp_second = @second;
    $tmp = shift(@tmp_second);
    if (@tmp_second > 0){
        do_smth(@first, @tmp_second);
    }

}
A: 

You are shifting the (undefined) scalars $tmp_first and $tmp_second.

Haven't looked any further.

Colin Fine
This isn't an answer, it should have been a comment.
Daenyth
+5  A: 

This code does not even compile. Without warnings and strict you will get these errors:

Type of arg 1 to shift must be array (not scalar dereference) at so.pl line 5, near "$tmp_first)"
Type of arg 1 to shift must be array (not scalar dereference) at so.pl line 10, near "$tmp_second)"
Execution aborted due to compilation errors.

and with warnings and strict:

Illegal character in prototype for main::do_smth : @first,@second at so.pl line 4.
Global symbol "@first" requires explicit package name at so.pl line 5.
Global symbol "$tmp" requires explicit package name at so.pl line 6.
Global symbol "$tmp_first" requires explicit package name at so.pl line 6.
Type of arg 1 to shift must be array (not scalar dereference) at so.pl line 6, near "$tmp_first)"
Global symbol "@second" requires explicit package name at so.pl line 8.
Global symbol "@second" requires explicit package name at so.pl line 10.
Global symbol "$tmp" requires explicit package name at so.pl line 11.
Global symbol "$tmp_second" requires explicit package name at so.pl line 11.
Type of arg 1 to shift must be array (not scalar dereference) at so.pl line 11, near "$tmp_second)"
Global symbol "@first" requires explicit package name at so.pl line 13.
Execution aborted due to compilation errors.

I dont know what you are trying to do, but here is your code with the proper syntax:

use warnings;
use strict;

sub do_smth (\@\@);  # predeclaration needed since the prototyped sub
                     # is called recursively
sub do_smth (\@\@) {
    my ($first, $second) = @_;
    my @tmp_first = @$first;
    my $tmp = shift(@tmp_first);
    if (@tmp_first > 0){
        do_smth(@tmp_first, @$second);
    }
    my @tmp_second = @$second;
    $tmp = shift(@tmp_second);
    if (@tmp_second > 0){
        do_smth(@$first, @tmp_second);
    }
}
Eric Strom
@Daenyth => That's not what its doing, a `(\@\@)` prototype imposes array reference context on 2 required arguments. That way you call it with `do_smth @one, @two` rather than `do_smth \@one, \@two`
Eric Strom
@Eric: You're right actually. I'm just so used to seeing it misused by people who think it's for argument signatures. I'll try to keep my kneejerking to a minimum next time ;)
Daenyth