Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex print first instance 1

Status
Not open for further replies.

stevio

Vendor
Jul 24, 2002
78
AU
Hi there,

Have a simple script which runs a command on the system and returns the regex value
Code:
my @val = `command here`;
    
        foreach $line(@val) {           
           if ($line =~ /(test\d+)/){
             print "$1\n";
           }
        }
The question is, I only want to print the first value that it returned if more than one is found, but at the same work through each line. So if the resulting text of the command was:

__DATA__

Test1
Test6
Test5
Test1

I only want to print out the first Test1

Any help appreciated

 
Use a hash to store the regexp matches and skip any that is already in the hash.

Code:
my @val = `command here`;
my %seen;    
foreach $line(@val) {           
   if ($line =~ /(test\d+)/){
      print "$1\n" if ++$seen{$1} == 1;
   }
}

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Or maybe this would work better...
Code:
if ( lc ( $line ) =~ /(test\d+)/ )
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top