--- Jeff 'japhy/Marillion' Pinyan <[EMAIL PROTECTED]> wrote:
> On Aug 20, Paul Johnson said:
> 
> >On Mon, Aug 20, 2001 at 08:27:41AM -0400, Jeff 'japhy/Marillion' Pinyan wrote:
> >
> >>   $str =~ /\s*/;
> >>   my $leading = length $1;
> >
> >that would be
> >
> >    $str =~ /(\s*)/;

Haven't seen the rest of the thread, so I'm guessing the requirements from the subject 
line.

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

First, I added the caret to force matching from the beginning of the line so we don't 
accidentally
match embedded whitespace.  That may or may not matter, depending upon the structure 
of the data,
but since I haven't seen the rest of the thread, I'm not sure.

The above snippet works, but not necessarily for reasons that are clear to Perl 
beginners.  Since
the asterisk matches "zero or more", it will always allow that regex to succeed, 
regardless of
whether there is any whitespace.  Thus, $1 is always set.

However, my first inclination, upon seeing that regex, was to change the asterisk to a 
plus so
that we only match when there's a match.  This is usually more efficient.  In this 
case, however,
that breaks the code.

    "    abc"  =~ /^(\s*)/;
    my $string = "abc";
    $string    =~ /^(\s+)/;
    print length $1;

The above snippet prints '4' because the second regex failed to match, leaving $1 
equal to 4
spaces.  As a result, I prefer to use the "dollar number" variables ($1, $2, etc.) 
only when
testing for success of the regex:

    my $leading = $str =~ /^(\s+)/ ? length $1 : 0;

    # or

    my $leading = 0;
    if ( $str =~ /^(\s+)/ ) {
        $leading = length $1;
    }

I only bring this up because I'd hate to see someone grab that snippet, make a quick 
modification,
and then pull their hair out because it doesn't work.

Cheers,
Curtis "Ovid" Poe

PS:  Hi japhy :)


=====
Senior Programmer
Onsite! Technology (http://www.onsitetech.com/)
"Ovid" on http://www.perlmonks.org/

__________________________________________________
Do You Yahoo!?
Make international calls for as low as $.04/minute with Yahoo! Messenger
http://phonecard.yahoo.com/

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to