G'day perl-diddler,

Firstly, I suggest you read "perlop: Regexp Quote-Like Operators". There are certain things about qr that are non-standard and non-intuitive: I suspect you're making understandable, yet incorrect, assumptions.

In the following, I've addressed all (I think) of the points you've raised and hopefully cleared up any misunderstandings.

When used as a string, qr acts like a string:

$ perl -E 'my $re = qr{([0-6BS])}; say $re' (?^u:([0-6BS]))

When used as a reference, qr acts like a reference:

$ perl -E 'my $re = qr{([0-6BS])}; say ref($re)' Regexp

When used as a hash key, which is a string, qr acts like a string:

$ perl -E 'my $re = qr{([0-6BS])}; my %x = ($re, 1); my @y = keys %x; +say $y[0]' (?^u:([0-6BS]))

The hash key is just a string, not a reference:

$ perl -E 'my $re = qr{([0-6BS])}; my %x = ($re, 1); my @y = keys %x; +say "|", ref($y[0]), "|"' ||

The next two points directly address the title of your post: "how to use string RE (against $_ and capture)".

You can use qr in a match like '/COMPILED_QR_RE/':

$ perl -E 'my $re = qr{([0-6BS])}; $_ = "B"; /$re/; say $1' B

You can use a hash key string in a match like '/STRING_RE/':

$ perl -E 'my $re = qr{([0-6BS])}; my %x = ($re, 1); my @y = keys %x; +$_ = "B"; /$y[0]/; say $1' B

See also: perlre and ref.

— Ken


In reply to Re: how to use string RE (against $_ and capture) by kcott
in thread how to use string RE (against $_ and capture) by perl-diddler

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.