in reply to variable interpolation sans character interpolation

In response to your updated question,

my $name = '(\w[\w-]*\w?)'; # any valid hostname segment my $nnam = "(($name\\.)*$name)"; # one or more "name" segments my %domainnames = ( "$nname\\.com" => 'a commercial domain', "$nname\\.edu" => 'an educational institution', );

is a solution. When quoting that with double quotes, you need to escape $ (unless you want interpolation), @ (unless you want interpolation), " and \ by preceeding them with \, so the regexp is $nname\.com would be "$nname\\.com" as a string literal.

But it's simpler to use qr/.../ (like I suggested in my earlier post):

my $name = qr/(\w[\w-]*\w?)/; # any valid hostname segment my $nnam = qr/(($name\.)*$name)/; # one or more "name" segments my %domainnames = ( qr/$nname\.com/ => 'a commercial domain', qr/$nname\.edu/ => 'an educational institution', );

However, it's a big waste to stringify a compiled regexp, so you might want to alter your structure for a major speed boost. I doubt you actually need a hash, so here's a solution using an array:

my $name = qr/(\w[\w-]*\w?)/; # any valid hostname segment my $nnam = qr/(($name\.)*$name)/; # one or more "name" segments my @domainnames = ( { re => qr/$nname\.com/, desc => 'a commercial domain' }, { re => qr/$nname\.edu/, desc => 'an educational institution' }, );

If you really do need a hash:

my $name = qr/(\w[\w-]*\w?)/; # any valid hostname segment my $nnam = qr/(($name\.)*$name)/; # one or more "name" segments my @domainnames = ( qr/$nname\.com/ => 'a commercial domain', qr/$nname\.edu/ => 'an educational institution', ); my %domainnames; foreach (0 .. @domainnames/2-1) { $domainnames{$domainnames[$_*2+0]} = { re => $domainnames[$_*2+0], desc => $domainnames[$_*2+1], }; }

Replies are listed 'Best First'.
Re^2: variable interpolation sans character interpolation
by vacant (Pilgrim) on Oct 28, 2005 at 03:05 UTC
    Thanks very much, I think this is just what I needed. Just to make certain I understand what is going on,\ here, let me see if I can explain it to myself.

    The qr// operator creates a compiled re from the string it is given, and this compiled re can be passed in a variable. However, because it is no longer a string (it is a special variable type??) any backslashes it originally contained are no longer subject to interpolation even when a string which contains it as a variable is itself contained in another string, and so on. Is that about right?

    I also think you are right about using an array instead of a hash, particularly because I may want to add more fields to it.

    Thanks again.

      Sounds right. \ is interpretted at compile time in both cases. "..." returns a string with the slashes removed, and qr/.../ returns a compiled regexp (that stringifies to the slashed form, such as when used as a hash key).