[TriLUG] YAPQ (yet another perl question)..
Kevin Hunter
hunteke at earlham.edu
Thu Jun 11 18:05:00 EDT 2009
At 3:24pm -0400 on Thu, 11 Jun 2009, Greg Brown wrote:
> so close:
>
> 15998976 bytes total (8083968 bytes free)
> routername#Total bytes: 15998976
> Free bytes: 8
>
> so it's picking up the total bytes but on the free bytes it's only picking
> up the last digit of the total free.
This is because operators, for performance reasons, are "greedy" unless
told otherwise. So, the '.*' is matching as much as possible before it
lets the [0123456789]+ match. To correct it, I'd suggest being 100%
explicit in what you want:
>> $string =~ m/([0123456789]+) bytes total.*([0123456789]+) bytes free/;
$string =~ m/^(\d+) bytes total \((\d+) bytes free/;
or
$string =~ m/^(\d+) bytes total.*?(\d+) bytes free/;
^ - Make sure to start the match at the beginning of the line
\d - shorthand for [0123456789]
* - match preceding character as many times as possible
*? - match preceding character as few times as possible
I'd suggest the first form, as it's more explicit. Most folks can't
read regular expressions, so wherever possible, I suggest you make them
as simple *and explicit* as you can.
Cheers,
Kevin
More information about the TriLUG
mailing list