How can I count the number of spaces at the beginning of a line in Perl?

How to count the number of spaces at the beginning of a line in Perl?

Now I have:

  $temp = rtrim($line[0]);
  $count = ($temp =~ tr/^ //);

But that gives me an account of all the gaps.

+3
source share
6 answers
$str =~ /^(\s*)/;
my $count = length( $1 );

If you just need the actual spaces (instead of spaces) then this would be:

$str =~ /^( *)/;

: , tr , . , $count = ( $temp =~ tr/^ // );, ^ (. cjm), , . tr ^ ", ", ", ^".

+10

, @-. , :

#!/usr/bin/perl

use strict;
use warnings;

for my $s ("foo bar", " foo bar", "  foo bar", "  ") {
        my $count = $s =~ /\S/ ? $-[0] : length $s;
        print "'$s' has $count whitespace characters at its start\n";
}

, , @+, :

#!/usr/bin/perl

use strict;
use warnings;

for my $s ("foo bar", " foo bar", "  foo bar", "  ") {
    $s =~ /^\s*/;
    print "$+[0] '$s'\n";
}
+4

script, stdin. .

  #!/usr/bin/perl

  while ($x = <>) {
    $s = length(($x =~ m/^( +)/)[0]);
    print $s, ":", $x, "\n";
  }
+1

tr///not a regular expression operator. However, you can use s///:

use strict; use warnings;

my $t = (my $s = " \t\n  sdklsdjfkl");
my $n = 0;

++$n while $s =~ s{^\s}{};
print "$n \\s characters were removed from \$s\n";

$n = ( $t =~ s{^(\s*)}{} ) && length $1;
print "$n \\s characters were removed from \$t\n";
+1
source

Since regular expression matching returns a match in parentheses when called in a list context, the CanSpice response can be written in one expression:

$count = length( ($line[0] =~ /^( *)/)[0] );
+1
source

Sends the number of spaces

echo "   hello" |perl -lane 's/^(\s+)(.*)+$/length($1)/e; print'

3

+1
source

Source: https://habr.com/ru/post/1769188/


All Articles