Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the amount of spaces at the start of a string in Perl?

Tags:

regex

perl

How can I count the amount of spaces at the start of a string in Perl?

I now have:

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

But that gives me the count of all spaces.

like image 223
edelwater Avatar asked Dec 01 '22 09:12

edelwater


1 Answers

$str =~ /^(\s*)/;
my $count = length( $1 );

If you just want actual spaces (instead of whitespace), then that would be:

$str =~ /^( *)/;

Edit: The reason why tr doesn't work is it's not a regular expression operator. What you're doing with $count = ( $temp =~ tr/^ // ); is replacing all instances of ^ and with itself (see comment below by cjm), then counting up how many replacements you've done. tr doesn't see ^ as "hey this is the beginning of the string pseudo-character" it sees it as "hey this is a ^".

like image 194
CanSpice Avatar answered Dec 06 '22 09:12

CanSpice