wilbur has asked for the wisdom of the Perl Monks concerning the following question:

What the heck is the syntax to assign a regex from an array into a key?
@array = (qr/^foo /, qr/bar$/); my %hash(@array) = ()
I am using tie::RegexpHash and that works if I do it manually %hash{/^foo/} but I need to get it to work from an array.

Replies are listed 'Best First'.
Re: Assigning regex from arrays to hash keys
by jeffa (Bishop) on Apr 28, 2004 at 20:57 UTC
    use strict; use warnings; use Data::Dumper; my %hash; my @value = (qr/^foo /, qr/bar$/); my @key = qw(foo bar); @hash{@key} = @value; print Dumper \%hash;

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      that gets the regex in the value, I need it in the key.
Re: Assigning regex from arrays to hash keys
by dave_the_m (Monsignor) on Apr 28, 2004 at 21:28 UTC
    Well, its not entirely clear from your description what you're asking, but assuming that Tie::RegexpHash is something that allows regexes to be used as keys, then you'll need

    my %hash; tie %hash, 'Tie::RegexHash'; @hash{@array} = ();

    Note that the my declaration can't be included with the hash access, the hash needs to be tied first, and it's @hash{..} not %hash{...} for slicing.

Re: Assigning regex from arrays to hash keys
by revdiablo (Prior) on Apr 28, 2004 at 21:43 UTC

    As dave_the_m mentions, you seem to be a bit confused with your sigils. You know, those funny little characters that go in front of variables in Perl. Your use is consistent with the designs for Perl6, but back here in Perl5 land (i.e. now, not in the future) we still have to use $ when we're accessing a single value and @ when we're accessing a list of values. In both your examples of hash access -- %hash(@array) and %hash{/^foo/} -- you picked the wrong one. Those should be @hash{@array} and $hash{/^foo/}. In the first you have another syntax error, too: those parentheses should be curly brackets. Perhaps it's time to refresh yourself on Perl's syntax. You might find perlcheat to be a handy chart.

    HTH

Re: Assigning regex from arrays to hash keys
by pelagic (Priest) on Apr 29, 2004 at 06:28 UTC
    You assigned a array to a hash. This operation does a nice key - value kinda grouping of the array values. So your first re got a key and your second re got a value.
    #!/usr/bin/perl use strict; my @array = (qr/^foo /, qr/bar$/); print "@array\n"; my %hash = map {$_, 1} @array; foreach (keys %hash) { print "$_\n"; }

    pelagic