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.
$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 ^
".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With