user3069232
user3069232

Reputation: 8995

Making iteration recursive using PERL

Bon,

I have this code which is a simple loop, which works… to call it you need to send it a reference to an array of numbers.

@blah = (0b0010,0b010,0b0111);
$ans = &logical_loop(\@blah);

sub logical_loop()
{
    my $codes = $_[0];
    my $ans = 0;
    foreach (@$codes) {
        printf "%b\n",$_;
    $ans = ($ans | $_)
    }
    return($ans);
}

I wanted to make it recursive, so I wrote this code which doesn't work…. please can somebody tell me what I have missed? something to do with variables scopes perhaps?

sub recursive_loop 
{
    my $codes = $_[0];
    my $el = shift @$codes;
    if (@$codes == ()) {
        return ($el | $answer);
    } else {
        $answer = (&recursive_loop(\@$codes) | $el);
    }
}

Upvotes: 0

Views: 159

Answers (2)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26131

sub recursive_loop {
  return 0 unless @_;
  my $head = shift;
  return $head | recursive_loop(@_);
}

@blah = (0b0010,0b010,0b0111);
recursive_loop(@blah);

More efficient tail recursive:

sub or_it_up {
  unshift @_, 0;
  goto &recursive_loop;
}

sub recursive_loop {
  my $ans = shift;
  return $ans unless @_;
  unshift @_, $ans | shift;
  goto &recursive_loop;
}

@blah = (0b0010,0b010,0b0111);
or_it_up(@blah);

You can use calling recursive_loop as function but in this way it will not make stack frame.

You can also write it simply without or_it_up which serves just educational purpose. Calling recursive_loop directly will make result caused by nature of binary or.

Upvotes: 1

Pierre
Pierre

Reputation: 1246

I see a few problems with your subroutine.

  • its name contains a spacing mark
  • it doesn't call itself therefore no recursion is possible

Upvotes: 1

Related Questions