Matching Only Once in Perl


There is a simpler version of the match operator in Perl - the ?PATTERN? operator. This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset.

For example, you can use this to get the first and last elements within a list −

Example

 Live Demo

#!/usr/bin/perl
@list = qw/food foosball subeo footnote terfoot canic footbrdige/;
foreach (@list) {
   $first = $1 if /(foo.*?)/;
   $last = $1 if /(foo.*)/;
}
print "First: $first, Last: $last\n";

When the above program is executed, it produces the following result −

First: foo, Last: footbrdige

Updated on: 29-Nov-2019

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements