in reply to Re: counting leading white spaces
in thread counting leading white spaces
Your code has an error. It reports the wrong number of leading tabs if there are some characters in the line that you didn't cater for:
sub countLeadingTabSpaces { my($data) = @_; my @string=split(/\t/,$data); my $numberofLeadingTabs=0; my $size = @string; my $TabSpace = ""; my $loopBreak = 0; for (my $count = 0; $count < $size; $count++) { if($loopBreak==0) { if($string[$count] =~/([A-Za-z0-9@])/) { $loopBreak = 1; }else{ ++$numberofLeadingTabs; } } } print "=>NumberofLeadingTabs: ".$numberofLeadingTabs; return $numberofLeadingTabs; } countLeadingTabSpaces("\t\t!\tfoo"); # prints "3" but only has two lea +ding tabs!
It's better to avoid split and then checking whether a line contains a certain set of characters, and instead just count the number of tab characters at the start:
my $numberofLeadingTabs = 0; if ($data =~ /^(\t+)/) { my $tabs = $1; $numberofLeadingTabs = length $tabs; };
|
|---|