FAQ 6.18 Why does using $&, $`, or $' slow my program down?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
This is an excerpt from the latest version perlfaq6.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


6.18: Why does using $&, $`, or $' slow my program down?

    (contributed by Anno Siegel)

    Once Perl sees that you need one of these variables anywhere in the
    program, it provides them on each and every pattern match. That means
    that on every pattern match the entire string will be copied, part of it
    to $`, part to $&, and part to $'. Thus the penalty is most severe with
    long strings and patterns that match often. Avoid $&, $', and $` if you
    can, but if you can't, once you've used them at all, use them at will
    because you've already paid the price. Remember that some algorithms
    really appreciate them. As of the 5.005 release, the $& variable is no
    longer "expensive" the way the other two are.

    Since Perl 5.6.1 the special variables @- and @+ can functionally
    replace $`, $& and $'. These arrays contain pointers to the beginning
    and end of each match (see perlvar for the full story), so they give you
    essentially the same information, but without the risk of excessive
    string copying.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Re: FAQ 6.18 Why does using $&, $`, or $' slow my program down?

Quoted text here. Click to load it

Should this answer mention $ &c. from 5.10?


  Joy and Woe are woven fine,
  A Clothing for the Soul divine       William Blake
  Under every grief and pine          'Auguries of Innocence'
  Runs a joy with silken twine.                                ben@morrow.me.uk

Re: FAQ 6.18 Why does using $&, $`, or $' slow my program down?

Quoted text here. Click to load it

Yes it should. I'll update the answer on my next pass.


Site Timeline