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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parse Line to capture desired string 1

Status
Not open for further replies.

aaiqbal

Programmer
Sep 15, 2003
26
US
Hi Everyone,
I'm new to this forum. I'm just starting to use Perl and I know how to read a line from a file and that it gets stored in "$_". I also know how to search for a string within $_. What I can't figure out is when that string is found, how do I get (or print) just that string from within the line? Any help would be appreciated. Thanks.
 
Use the parentheses to capture the string you search for. Each set of parentheses in a regex is stored in a special variable. The special variables are $1, $2, $3, etc. You can then print the value of $1.

$_ =~ /some pattern (this will be captured) and more stuff/;
print $1; # will print "this will be captured";

or you can just assign the contents of the parentheses directly to a variable as follows:

my ($string) = $_ =~ /(your search pattern here)/;


if you have more than one set of parentheses, do this:

my ($first, $second, $third) = $_ =~ /(first)(second)(third)/;

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top