3

我有一个 Perl 子程序,它询问用户的输入。我在该子例程本身内部执行检查输入的输入是否为有效输入。

如果不是,我想再次调用子程序,让用户这次输入有效的输入。

我的子程序如下:

sub some_routine {    
    print "Enter a number to select   (1) Apple (2) Mango (3) grapes:"
    $value=STDIN;
    if($value =~ /[^1-3]/ ) {
        print "The input is not valid!";
        print "Do you want to continue selecting a fruit again (Y or N)?";
        $choice = STDIN;
        if( $choice eq "y") {
            ### I want to call the subroutine again to enter input ###
          } else {
            exit;
        }
    }
}

那么如何在其中递归一个子程序呢?

4

9 回答 9

10

要在 Perl 中递归调用子例程,您只需从自身调用子程序,就像在任何其他语言中一样:

sub factorial {
  my $num = shift;
  return 1 if $num < 2;
  return $num * factorial($num - 1);
}

但是,您真的不想将递归用于“重复直到条件改变”的场景。
这就是while循环的用途

my $valid;
while (!$valid) {
  print "Enter something: ";
  my $data = <STDIN>;
  $valid = validate($data);
  print "Bzzt!  Invalid - try again!\n" unless $valid;
}
于 2009-09-29T07:04:16.130 回答
7

没有理由为此使用递归。一个简单的while循环就可以了。

my $input_valid = 0;
while( !$input_valid ) { 
    print "Enter some input: ";
    my $input = <STDIN>;
    $input_valid = validate_input( $input );
}

如果validate_input返回 0,循环将重复。

于 2009-09-29T07:03:55.437 回答
4

recursive

sub select_fruit {    
    print "Enter a number to select   (1) Apple (2) Mango (3) grapes:"
    $value=<STDIN>;
    if($value =~ /[^1-3]/ ) {
        print "The input is not valid!";
        print "Do you want to continue selecting a fruit again (Y or N)?";
        $choice = <STDIN>;
        if( $choice eq "y") {
            $value = select_fruit();
          } else {
            exit;
        }
    }
    return $value;
}

goto - Tail Call Optimization (TCO)

sub select_fruit {
    print "Enter a number to select   (1) Apple (2) Mango (3) grapes:"
    $value=<STDIN>;
    if($value =~ /[^1-3]/ ) {
        print "The input is not valid!";
        print "Do you want to continue selecting a fruit again (Y or N)?";
        $choice = <STDIN>;
        if( $choice eq "y") {
            goto &select_fruit;
          } else {
            exit;
        }
    }
    return $value;
}

or redo

sub select_fruit {
SELECT_FRUIT: {
       print "Enter a number to select   (1) Apple (2) Mango (3) grapes:"
       $value=<STDIN>;
       if($value =~ /[^1-3]/ ) {
           print "The input is not valid!";
           print "Do you want to continue selecting a fruit again (Y or N)?";
           $choice = <STDIN>;
           if( $choice eq "y") {
               redo SELECT_FRUIT; # same as goto SELECT_FRUIT;
             } else {
               exit;
            }
        }
        return $value;
    }
}

and so ...

于 2009-09-29T10:50:45.970 回答
4

调用例程的正确方法是

goto &some_routine;

...因为你有一个尾调用 - 这是你在你的函数中做的最后一件事。如果您正常调用它,则每次调用都会占用一个堆栈帧,并且内存分配会增加。像这样调用,你重复使用相同的堆栈帧。从您作为程序员的角度来看,这与

return some_routine(@_);

但不吃记忆。

适用于将自己称为最后一件事的例程 - 在其他情况下,您确实应该切换到其他人建议的 while 循环(并且,为了代码的吸引力,您可能无论如何都想这样做)。

于 2009-09-29T08:44:51.230 回答
2
my $value;
until(defined $value = get_value()) {
  print"you didn't enter a valid value\n";
}

sub get_value {
 print "Enter a number to select   (1) Apple (2) Mango (3) grapes:"
    $value=<STDIN>;
    if($value =~ /[1-3]/ ) {
        return $value;
    } else {
        return undef;     
    }
}
于 2009-09-29T08:05:59.657 回答
2

编辑:出于各种原因(风格、性能等),我强烈建议不要在这里进行递归调用,而是在 while 循环中检查它

[原始回答者的免责声明]“从风格的角度来看,我不会在这里进行递归调用,而是在 while 循环中检查它,但我想在某种程度上,这也是一个品味问题。”

就使用递归而言,例如,您可以从函数内部调用函数,如下所示:

sub get_positive_number {
    print "Please enter a positive number: ";
    my $number = <STDIN>;
    chomp $number;
    if ($number > 0) {
        return $number;
    }
    else {
        return get_positive_number();
    }
}

my $result = get_positive_number();
print "result: $result\n";
于 2009-09-29T07:03:54.477 回答
1

使用IO::Prompt模块。

有了它,你可以这样写:

use IO::Prompt;
my @choices = qw( Apple Mango Grapes );
my $answer = prompt("Select :", "-menu" => \@choices);
print $answer;
于 2009-09-30T05:27:28.580 回答
0

您的输入不是 eq "y" 而是 "y\n"。

如果将行更改if ($choice =~ /^[Yy]/)为此将确保您在输入开始时捕获 Y,而不必担心 y 或 yes 或 Y 或 Yes。

作为帮助,您应该使用<STDIN>而不是STDIN单独使用。始终use strict; use warnings;在顶部添加。这确保您需要使用以下方法定义 $value 和 $choice:

my $value = '';
my $choice = '';

正如其他人所提到的。作为一个循环,这可能更简单。

#!/usr/bin/env perl
use strict;
use warnings;

some_routine();

sub some_routine {    
    my $value = '';
    my $choice = '';
    print "Enter a number to select   (1) Apple (2) Mango (3) grapes:";
    $value = <STDIN>;
    if($value !~ /[1-3]/ ) {
        print "The input is not valid!";
        print "Do you want to continue selecting a fruit again (Y or N)?";
        $choice = <STDIN>;
        if( $choice =~ /[Yy]/) {
            some_routine();
          } else {
            exit;
        }
    }
}
于 2009-10-01T13:25:31.403 回答
0

我使用的是一个简单的 goto:

START:
print "\n Name of the country (any one out of: china, japan or tokyo): ";
my $country_name = <>;
chomp($country_name);

unless ($country_name eq "china" || $country_name eq "japan" ||
    $country_name eq "tokyo") {
    print "\n Invalid country name entered. Please try again. \n";
    goto START;
}

这是一种非常幼稚的方法,但适用于初学者。

于 2010-12-01T19:24:54.167 回答