in reply to counting leading white spaces

Hi you can use below method for the same

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; }

Replies are listed 'Best First'.
Re^2: counting leading white spaces
by Corion (Patriarch) on Apr 27, 2011 at 09:46 UTC

    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; };