简体   繁体   中英

Perl "scalar" function returning "1" on an empty array

The following Perl code will print a "1", however the function test2 really has no legitimate input value. Why does Perl act this way?

test();

sub test {
    my ($var) = @_;

    test2($var);
}

sub test2 {
    my (@array) = @_;
    print scalar @array;
}

test2($var) passes one scalar to test2 ( $var ), so one scalar is assigned to @array by my (@array) = @_; .

The value of the scalar in question ( $var ) is undef , since you assigned "nothing" to $var in my ($var) = @_; .

Maybe you want test2(@_) (passes the zero scalars in @_ ) instead of test2($var) (passes the one scalar $var )?

Inside test , $var is set to undef by the assignment. So your call to test2 passes a list with one element, undef .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM