What are the Perl equivalents of return and continue keywords in C?

后端 未结 3 787
梦毁少年i
梦毁少年i 2021-02-03 23:47

I am getting this error when I use this code

sub search {
    my ($a, @a_list) = @_;
    foreach (@a_list) {
        if($_ == $a) return TRUE;
        # continue         


        
3条回答
  •  萌比男神i
    2021-02-04 00:27

    Your question has been (very!) comprehensively answered by Jonathan, but I wanted to point out a few other, more perlish ways to replace your "search" function.

    use strict;
    use warnings;
    use 5.010;
    
    my @a_list = (1, 2, 3);
    my $a = 2;
    
    # If you're using 5.10 or higher, you can use smart matching.
    # Note that this is only equivalent if $a is a number.
    # That is, "2.0" ~~ ["1", "2", "3"] is false.
    say $a ~~ @a_list;
    
    # Need to install List::MoreUtils, not a standard module
    use List::MoreUtils qw(any);
    say any { $a == $_ } @a_list;
    
    # List::Util is a core module
    use List::Util qw(first);
    say defined first { $a == $_ } @a_list;
    
    # No modules used, but less efficient
    say grep { $a == $_ } @a_list > 0;
    

    For more info, see the documentation for smart matching, List::MoreUtils, List::Util and grep.

提交回复
热议问题