Is it possible to do something clever with regexes within a hash key?
E.g., in the following code, it's not possible to access $1, $2, ... from within the curly braces (or the regular braces for an array, though the list of matches returned in a regex is not as potentially useful in an array).
The following code isn't obfuscated, but it shows what I would like to be able to do.
$nerf{"my"} = "fridge";
$nerf{"0"} = "truth";
$nerf{"1"} = "beauty";
@nerf = ('i', 'love', 'cheese');
$_ = 'my funny valentine';
print "print ctxt 1: ", /^(\w*)/, " $&", "\n";
# good - this regex returns the
# match b/c it's a list context
print "print ctxt 2: ", /^\w*/, " $&", "\n";
# good - this regex returns a
# 1 b/c there are no parentheses
$x = $nerf{/^(\w*)/};
print "hash ctxt: ", $x, " $&", "\n";
# this regex returns a 1 despite the
# parentheses because it wants a scalar
# but dammit, i'd like to be able to do regexes
# within hash keys
$y = $nerf[/^(\w*)/];
print "array ctxt: ", $y, " $&", "\n"
# this regex also returns a 1 despite the parentheses
According to the Sacred Book (p. 209),
"One never needs to force evaluation in a list context, because any operation that wants a list already provides a list context to its list arguments for free."
But what if one is particularly ornery? Does anyone know a 1-line hack to get around this particular hashkey-regex instance?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.