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.
$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 ^ ", ", ", ^".
tr
$count = ( $temp =~ tr/^ // );
^
, @-. , :
@-
#!/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"; }
script, stdin. .
#!/usr/bin/perl while ($x = <>) { $s = length(($x =~ m/^( +)/)[0]); print $s, ":", $x, "\n"; }
tr///not a regular expression operator. However, you can use s///:
tr///
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";
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] );
Sends the number of spaces
echo " hello" |perl -lane 's/^(\s+)(.*)+$/length($1)/e; print'
3
Source: https://habr.com/ru/post/1769188/More articles:How do you play KahaDB message archives? - activemqЧто значит "переводить" графический объект? - terminologylxml, doctype missing during serialization - pythonNeed to provide page breaks in internal PdfPTable iTextSharp - c #php brackets and strings - variablesHow are out-of-parameters options for GObject bindings for Seed JavaScript presented? - cphp5 and namespace? - phpAvoiding slashes in sed - sedwhere, for example, above the cook (500) - sqlshell scripting: get the given range of parameters - shellAll Articles