#!/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! #### 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