[H-GEN] A perl query

Bruce Campbell bc at humbug.org.au
Mon May 5 07:41:30 EDT 2003


[ Humbug *General* list - semi-serious discussions about Humbug and     ]
[ Unix-related topics. Posts from non-subscribed addresses will vanish. ]

On Mon, 5 May 2003, Three Blokes wrote:

> Jason Parker-Burlingham <jasonp at uq.net.au> wrote:
> >                 s/$regex/$subs{$1}/g;
>
> One more clarification if you don't mind and then I will understand it all.
> In the above line, how does this expression know which value from %keys to
> substitute for the $regex that it's matched?,

The 'perlre' man page will explain this in painful detail, but assume that
you have a pattern to match the preceeding line, the $N values, where N is
a number, will be filled in by perl saving what it has been told to save,
being the sub-patterns within the '(' and ')' characters.

	if( $line =~ /^\S+\s+(\S+)\s+[^,]*,\s+(detail|but)\s+\S+\s+(\S+)\s*$/ ){
		print "1 is $1\n";
		print "2 is $2\n";
		print "3 is $3\n";
	}

This will print:

	1 is 'perlre'	- The '\S+' within the first set of '(' and ')'
	2 is but	- We were looking for either 'detail' or 'but'.
	3 is that	- The '\S+' within the third and last set of brackets.

> I'm assuming the {$1} is it,
> but what I want explained is how the compiler realises that $1 means the
> value that currently matches from $regex?, is that just a standard (so in
> every case where a match is found $1 will hold the value that was matched?

Yes, and you have more than one value that can be saved.

A common way of straining log files is:

	while( my $line = <INPUT> ){
		next unless( $line =~ /^(\d+):\s*(\S+)\s*:\s*(\S+)\s*:\s*(\S+.*)$/ );

> Thanks again guys for all your help, and sorry to be a nuisance.

--==--
Bruce.


--
* This is list (humbug) general handled by majordomo at lists.humbug.org.au .
* Postings to this list are only accepted from subscribed addresses of
* lists 'general' or 'general-post'.  See http://www.humbug.org.au/



More information about the General mailing list