LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   perl improve regex query (https://www.linuxquestions.org/questions/programming-9/perl-improve-regex-query-864288/)

kdelover 02-22-2011 08:10 AM

perl improve regex query
 
hi,

I want to get rid of the repetitive \s+(\d+) in my pattern.can any one suggest a better way of doing this.Thanks.



Code:

#!/usr/bin/perl
use strict;
use warnings;
my $mem=`cat /proc/meminfo`;
my @arr=$mem=~m/MemTotal:\s+(\d+).*MemFree:\s+(\d+).*SwapTotal:\s+(\d+).*SwapFree:\s+(\d+)/s;
map { print $_."\n" } @arr;

To get all the digits i can do this m/.*:\s+(\d+).*/g

Tinkster 02-22-2011 10:28 AM

Code:

my @arr=$mem=~m/(?:MemTotal|MemFree|SwapTotal|SwapFree):\s+(\d+)/gxs;

Cheers,
Tink

kdelover 02-22-2011 12:17 PM

Thanks its works! i had to dig a bit to see what exactly you were doing as i am new to perl & regex

i wanted to clear few things,the reason for using ?: is not to save the matched pattern in the memory?So,if you dont use ?: i guess $1 should contain MemTotal,MemFree,SwapTotal,SwapFree. Is that right?

i still find it little tricky how the patterning matching options are xs working,although i understand how g works in the above the example.

Thanks again !!

Tinkster 02-22-2011 01:46 PM

Quote:

Originally Posted by kdelover (Post 4267566)
Thanks its works! i had to dig a bit to see what exactly you were doing as i am new to perl & regex

i wanted to clear few things,the reason for using ?: is not to save the matched pattern in the memory?So,if you dont use ?: i guess $1 should contain MemTotal,MemFree,SwapTotal,SwapFree. Is that right?

Yup. Correctly assessed.

Quote:

Originally Posted by kdelover (Post 4267566)
i still find it little tricky how the patterning matching options are xs working,although i understand how g works in the above the example.

Thanks again !!

Heh. I'm sure you'll get the hang of it really soon. For some
in-depth coverage have a look at "Mastering regular expressions" in
your local library (or add it to your personal library) ... awesome
book, w/ a strong focus on RegEx & perl (while it also covers aspects
of RE's in other languages and a variety of regex engines).




Cheers,
Tink

kdelover 02-23-2011 12:14 AM

Cool.using only g works too.thanks


All times are GMT -5. The time now is 08:57 AM.