rachitmohta11 has asked for the wisdom of the Perl Monks concerning the following question:

I have a variable containing a string beginning with multiple tabs.
I need to find the number of tabs present in the beginning, preferably in one or two line, instead of writing a loop.
Please help!

Replies are listed 'Best First'.
Re: Simple regex related problem
by Corion (Patriarch) on Jun 24, 2010 at 06:52 UTC

    You don't show us the code you have already written. This makes it hard for us to suggest you ways to improve your code.

    You could use the following code, but it's likely even less efficient than a loop:

    my $string = "\t\t\tfoo\t\tbar"; $string =~ s/^(\t+).*/$1/; $string =~ s/\t/+1/g; print eval $string, " tabs";
Re: Simple regex related problem
by ikegami (Patriarch) on Jun 24, 2010 at 06:58 UTC

    By definition, it's impossible to repeat an action (check if the next character is a tab) an arbitrary number of times without using a loop.

    Of course, nothing's stopping you from using existing loops.

    my $num_leading_tabs = length( (/^(\t*)/)[0] );
Re: Simple regex related problem
by rovf (Priest) on Jun 24, 2010 at 07:40 UTC

    $string =~ /^(\t*)/; $number_of_initial_tabs=length($1);

    -- 
    Ronald Fischer <ynnor@mm.st>
Re: Simple regex related problem
by johngg (Canon) on Jun 24, 2010 at 12:44 UTC

    tr as an alternative to length.

    $ perl -E ' > $str = qq{\t\t\tcol1\tcol2}; > $str =~ m{^(\t+)}; > $leadingTabs = $1 =~ tr{\t}{}; > say $leadingTabs;' 3 $

    Cheers,

    JohnGG

Re: Simple regex related problem
by AnomalousMonk (Archbishop) on Jun 24, 2010 at 16:14 UTC

    The length-based approaches are probably a bit faster, but this also seems to work:

    >perl -wMstrict -le "my $s = qq{\t\t\tX\t\t}; my $n =()= $s =~ m{ \G \t }xmsg; print $n; " 3

    Update: Removed pointless capture group from regex.