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

后端 未结 6 1680
清歌不尽
清歌不尽 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

    0 讨论(0)
  • 2020-12-29 18:39

    Although 'length()' is the correct answer that should be used in any sane code, Abigail's length horror should be mentioned, if only for the sake of Perl lore.

    Basically, the trick consists of using the return value of the catch-all transliteration operator:

    print "foo" =~ y===c;   # prints 3
    

    y///c replaces all characters with themselves (thanks to the complement option 'c'), and returns the number of character replaced (so, effectively, the length of the string).

    0 讨论(0)
  • 2020-12-29 18:41

    The length() function:

    $string ='String Name';
    $size=length($string);
    
    0 讨论(0)
  • 2020-12-29 18:45
    perldoc -f length
    
       length EXPR
       length  Returns the length in characters of the value of EXPR.  If EXPR is
               omitted, returns length of $_.  Note that this cannot be used on an
               entire array or hash to find out how many elements these have.  For
               that, use "scalar @array" and "scalar keys %hash" respectively.
    
               Note the characters: if the EXPR is in Unicode, you will get the num-
               ber of characters, not the number of bytes.  To get the length in
               bytes, use "do { use bytes; length(EXPR) }", see bytes.
    
    0 讨论(0)
  • 2020-12-29 18:48
    length($string)
    
    0 讨论(0)
  • 2020-12-29 18:48

    Not an answer but an observation: I'm running v5.30.2 built for darwin-2level, and I've noticed that if I don't chomp my input first (as with stdin), then calculate the length, the length of a single character is not 1, but 2.

    Remember those newlines and other hidden characters that could be a factor.

    And I would love to find Abigail's post, but alas it seems to have been consumed by the ether.

    0 讨论(0)
提交回复
热议问题