Perl 5.10 has a nice feature that allows you to get the simplicity of the $'
solutions without the performance problems. You use the /p
flag and the ${^POSTMATCH}
variable:
use 5.010;
if( $string =~ m/^User-Agent:\s+/ip ) {
my $agent = ${^POSTMATCH};
say $agent;
}
There are some other tricks though. If you can't use Perl 5.010 or later, you use a global match in scalar context, the value of pos is where you left off in the string. You can use that position in substr:
if( $string =~ m/^User-Agent:\s+/ig ) {
my $agent = substr $string, pos( $string );
print $agent, "\n";
}
The pos is similar to the @+
trick that Axeman shows. I think I have some examples with @+
and @-
in Mastering Perl in the first chapter.
With Perl 5.14, which is coming soon, there's another interesting way to do this. The /r
flag on the s///
does a non-destructive substitution. That is, it matches the bound string but performs the substitution on a copy and returns the copy:
use 5.013; # for now, but 5.014 when it's released
my $string = 'User-Agent: Firefox';
my $agent = $string =~ s/^User-Agent:\s+//r;
say $agent;
I thought that /r
was silly at first, but I'm really starting to love it. So many things turn out to be really easy with it. This is similar to the idiom that M42 shows, but it's a bit tricky because the old idiom does an assignment then a substitution, where the /r
feature does a substitution then an assignment. You have to be careful with your parentheses there to ensure the right order happens.
Note in this case that since the version is Perl 5.12 or later, you automatically get strictures.