Is it possible to use a `named constant’ in a regex’s quantifiers?
I want to restrict the value of `word length’ to being stored in just the one place and so, using constant.pm (as described in Perl Debugged by Peter Scott and Ed Wright) I’ve come up with the following
#!/usr/local/perl/bin/perl
use strict;
use warnings;
use constant WORD_LENGTH => 9; # define constant value in one plac
+e
my $Word_Length = WORD_LENGTH; # mmm, is this the best I can do?
my $target_letters = 'x';
while ( $target_letters !~ /^[a-z]{$Word_Length}$/i ) {
print "Enter the " . WORD_LENGTH . " letters for today\n";
$target_letters = <STDIN>;
print "$target_letters\n";
}
…
… which works fine, but requires the extra $Word_Length variable that, something tells me, a good Perlophone would eschew 8-)
I'm aware (Perl Debugged again) that the `name constant' is constructed as a subroutine when it's defined, and returns its value when it's called. So I've tried ...{WORD_LENGTH()} based on `if it looks like a function, it is a function'. I also tried ...{&WORD_LENGTH} both with and without `()'s.
Monks advice keenly sought… /hagen
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|