Perl pos Function



This function is used to find the offset or position of the last matched substring. If SCALAR is specified, it will return the offset of the last match on that scalar variable.

You can also assign a value to this function (for example, pos($foo) = 20;) in order to change the starting point of the next match operation.

Offset is counter starting from zeroth position.


Following is the simple syntax for this function −

pos EXPR


Return Value

This function returns Integer in Scalar context and then positions of all the matches within the regular expression in List context.


Following is the example code showing its basic usage −

#!/usr/bin/perl -w

$name = "This is alpha beta gamma";
$name =~ m/alpha/g;

print("pos() ", pos($name), "\n");

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

pos() 13