如何从子程序中不返回任何内容? [英] How do I return nothing from a subroutine?

查看:61
本文介绍了如何从子程序中不返回任何内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在执行下一步之前验证条件,但只发出警告并跳过当前值而不是死亡.

I want to validate a condition before doing the next step, but only raise a warning and skip the current value instead of die-ing.

如何在不返回任何值的情况下重写 validate_me() 子程序?

How do I rewrite validate_me() subroutine without returning any value?

(更新) 请注意,以下代码按预期工作,只是我想要其他东西,而不是从 validate_me() 返回 1 或 0 仍然允许代码表现相同.

(Update) please note that the following code works as expected, it just that I want something else instead of returning 1 or 0 from validate_me() that still allow the code to behave the same.

foreach my $file ( @files ) {
    validate_me($foo, $bar, $baz) or next;
    do_something();
}  

sub validate_me {
    my ($foo, $bar) = @_;

    if ( $foo > $bar ) {
        carp("Something goes awol");
        return 0;
    }

    if ( $bar != $baz ) {
        carp("Odd");
        return 0;
    }

    return 1; # success
}

谢谢.

推荐答案

更新:

我想要其他的东西,而不是从 validate_me() 返回 1 或 0,这仍然允许代码表现相同.

I want something else instead of returning 1 or 0 from validate_me() that still allow the code to behave the same.

这是你的意思吗?请参阅eval.

Is this what you mean? See eval.

my @files = qw( a b c d e f );

FILES:
foreach my $file ( @files ) {
    eval { validate_me($file) };
    if (my $ex = $@) {
        warn "'$file' failed validation: $ex";
        next FILES;
    }
    print "$file passed\n";
}

sub validate_me {
    my ($file) = @_;
    die "Invalid filename\n" if 0.5 > rand;
    return; # explicitly return nothing
}

现在,明智的做法是将 validate_me 重构到其组件中:

Now, the sane thing to do would be to refactor validate_me into its components:

for my $file ( @files ) {
    if ( is_something_gone_awol($file, $mile) ) {
        warn "Something has gone awol: '$file' and '$mile'\n";
    }
    elsif ( is_something_odd($file, $smile) ) {
        warn "Something is odd: '$file' and '$smile'\n";
    }
    else {
        do_something($file);
    }
}

sub is_something_gone_awol {
    my ($foo, $bar) = 0;
    return $foo gt $bar;
}

sub is_something_odd {
    my ($bar, $baz) = @_;
    return $bar ne $baz;
}

这篇关于如何从子程序中不返回任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆