Perl return操作符

2021-07-04  本文已影响0人  PETJO

6. return 操作符

#!/usr/bin/perl

use strict;
use warnings;

my @names = qw( fred barney betty dino wilma pebbles bamm-bamm);
my $result = &which_element_is("dino", @names);
print $result . "\n\n";

sub which_element_is {
    my($what, @array) = @_;
    foreach (0..$#array) {
        if ($what eq $array[$_]) {
            return $_;
        }
    }
    -1    # 写成return -1 也行,但因为这里是最后一行,可以省略return,不过写了读起来更明朗些
}

sub Mul {
    my($a, $b) = @_;
    my $c = $a * $b; 
    # Return Value
    return($a, $b, $c); 
}

# Calling in Scalar context 
my $retval_sca = &Mul(25, 10);    # 只返回$c 
print ("Return value is $retval_sca\n" ); 
  
# Calling in list context 
my @retval_arr = &Mul(25, 10);    # 返回$a $b $c 
print ("Return value is @retval_arr\n" );
上一篇下一篇

猜你喜欢

热点阅读