# The \G Assertion in Perl

PERLServer Side ProgrammingProgramming Scripts

The \G assertion in Perl allows you to continue searching from the point where the last match occurred. For example, in the following code, we have used \G so that we can search to the correct position and then extract some information, without having to create a more complex, single regular expression −

## Example

Live Demo

#!/usr/bin/perl
$string = "The time is: 12:31:02 on 4/12/00";$string =~ /:\s+/g;
($time) = ($string =~ /\G(\d+:\d+:\d+)/);
$string =~ /.+\s+/g; ($date) = ($string =~ m{\G(\d+/\d+/\d+)}); print "Time:$time, Date: \$date\n";

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

Time: 12:31:02, Date: 4/12/00

The \G assertion is actually just the metasymbol equivalent of the pos function, so between regular expression calls you can continue to use pos, and even modify the value of pos (and therefore \G) by using pos as an lvalue subroutine.

Published on 29-Nov-2019 12:10:09