How can I count characters in Perl?

后端 未结 4 420
长发绾君心
长发绾君心 2021-01-11 12:09

I have the following Perl script counting the number of Fs and Ts in a string:

my $str = \"GGGFFEEIIEETTGGG\";
my $ft_count = 0;
$ft_count++ while($str =~ m/         


        
4条回答
  •  隐瞒了意图╮
    2021-01-11 12:48

    When the "m" operator has the /g flag AND is executed in list context, it returns a list of matching substrings. So another way to do this would be:

    my @ft_matches = $str =~ m/[FT]/g;
    my $ft_count = @ft_matches; # count elements of array
    

    But that's still two lines. Another weirder trick that can make it shorter:

    my $ft_count = () = $str =~ m/[FT]/g;
    

    The "() =" forces the "m" to be in list context. Assigning a list with N elements to a list of zero variables doesn't actually do anything. But then when this assignment expression is used in a scalar context ($ft_count = ...), the right "=" operator returns the number of elements from its right-hand side - exactly what you want.

    This is incredibly weird when first encountered, but the "=()=" idiom is a useful Perl trick to know, for "evaluate in list context, then get size of list".

    Note: I have no data on which of these are more efficient when dealing with large strings. In fact, I suspect your original code might be best in that case.

提交回复
热议问题