in reply to Question on Regex grouping
First, do not put parens '()' around things that you have no interest in using later. "Capturing" these things consumes time and resources and to no effect.
In general, I avoid using $1, $5 etc. Use Perl list slice instead. Assign directly to a variable like the code below shows. As you write more and more Perl code this $1, $2 stuff will appear less and less often.
This term m/abc\d{5}/ is a pre-condition - I have no problem at all with writing code that says: "forget this line if that pre-condition is not satisfied" and that is what the code below does.
Trying to compress things into a single statement gives Perl a bad name as a "write only" language and that reputation is undeserved! I am a big fan of both C and of Perl. It is easy to write obscure stuff in both languages, but you don't have to!
Update: ok a more obtuse solution:#!/usr/bin/perl -w use strict; my @x = ( 'smomedef12345', 'anabc12345 and there is some def12345678', 'qwerabc12345def55', 'def87654321abc54321', ); foreach (@x) { next unless (m/abc\d{5}/); #pre-condition to look further (my $string8) = m/def(\d{8})/; #puts $string8 in list context #$string8 = (m/def(\d{8})/)[0]; #alternate way with list slice if ( !defined($string8) ) { $string8 = 'undefined'; #Perl 5.10 has a special way to do this #Probably here just do "next;" # because an undefined value means the # regex above did not match! } print "var def=$string8\n"; } __END__ prints: ..note that first item is silently skipped! var def=12345678 var def=undefined var def=87654321 #note that this works even though #the pre-condition of abc\d{5} #occurs later in the line! Wow!
Does essentially the same thing but in a much more obtuse way.my @x = ( 'smomedef12345', 'anabc12345 and there is some def12345678', 'qwerabc12345def55', 'def87654321abc54321', ); print map{ /abc\d{5}/ and /def(\d{8})/ ? "def=$1\n" : () }@x; __END__ prints: def=12345678 def=87654321
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Question on Regex grouping
by JavaFan (Canon) on Dec 21, 2010 at 11:33 UTC | |
by Marshall (Canon) on Dec 21, 2010 at 13:17 UTC | |
by JavaFan (Canon) on Dec 21, 2010 at 13:57 UTC | |
by Marshall (Canon) on Dec 21, 2010 at 15:10 UTC | |
by JavaFan (Canon) on Dec 21, 2010 at 16:31 UTC | |
by TenThouPerlStudents (Initiate) on Dec 22, 2010 at 03:12 UTC | |
by TenThouPerlStudents (Initiate) on Dec 22, 2010 at 03:42 UTC | |
by JavaFan (Canon) on Dec 22, 2010 at 11:44 UTC | |
by TenThouPerlStudents (Initiate) on Dec 22, 2010 at 18:39 UTC | |
by TenThouPerlStudents (Initiate) on Dec 22, 2010 at 03:50 UTC | |
by AnomalousMonk (Archbishop) on Dec 22, 2010 at 05:29 UTC | |
|
Re^2: Question on Regex grouping
by ajguitarmaniac (Sexton) on Dec 21, 2010 at 09:09 UTC |