How do I get the length of a string in Perl?

后端 未结 6 1695
清歌不尽
清歌不尽 2020-12-29 18:14

What is the Perl equivalent of strlen()?

6条回答
  •  暖寄归人
    2020-12-29 18:32

    You shouldn't use this, since length($string) is simpler and more readable, but I came across some of these while looking through code and was confused, so in case anyone else does, these also get the length of a string:

    my $length = map $_, $str =~ /(.)/gs;
    my $length = () = $str =~ /(.)/gs;
    my $length = split '', $str;
    

    The first two work by using the global flag to match each character in the string, then using the returned list of matches in a scalar context to get the number of characters. The third works similarly by splitting on each character instead of regex-matching and using the resulting list in scalar context

提交回复
热议问题