Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Subroutine pos seems to just return the position of last match in the string.

And I wonder why is it possible to assign a value to it?
pos($string) = 1;

Replies are listed 'Best First'.
Re: How is assigning to pos() possible?
by kcott (Archbishop) on Jun 27, 2015 at 05:41 UTC

    This is documented in pos. That page contains links providing additional information.

    For future reference, you can find documentation for Perl's functions via "Perl functions A-Z".

    -- Ken

Re: How is assigning to pos() possible?
by davido (Cardinal) on Jun 27, 2015 at 05:41 UTC

    Within a regular expression, \G, used in conjunction with the /g modifier, matches at the position in the target string where the previous match left off. pos also contains the position where the previous match ended. They are tightly related; setting pos to a number makes \G match at that position within the target string.

    It has various other side-effects with respect to how m//g work, so see perlretut for a more thorough explanation.


    Dave

Re: How is assigning to pos() possible?
by Anonymous Monk on Jun 27, 2015 at 14:28 UTC

    In case you're also wondering more generally why it's possible to assign something to a function, the answer is that it is an "lvalue" sub. Another notable example of such a function is substr:

    my $foo = "Hello, World!"; substr($foo,7,5) = "PerlMonks"; print "$foo\n"; __END__ Hello, PerlMonks!

    You can even write Lvalue subroutines yourself:

    my $value; sub foo : lvalue { $value } foo() = "Bar"; print "$value\n"; __END__ Bar

    However, at least in my experience, they're only really useful in a few rare circumstances.