develooper Front page | perl.perl6.users | Postings from April 2020

regex objects as hash keys

Thread Next
Joseph Brenner
April 6, 2020 01:03
regex objects as hash keys
Message ID:
I find in Raku that (as expected) I can use an object as a hash key:

    class Rutabaga { method color { say "purple (and white)"; } }

    my $obj =
    my %vegeout;
    %vegeout{ $obj } = "this works";

And for something I was doing I wanted to save up
data about matches for various different regexs,
so I thought I could just use a hash for this, like so:

    my (%match_locs, $loc);

    my $godzilla_rx  = rx:i{ << godzilla >> };
    if $text ~~ m/$godzilla_rx/ {
        $loc = $/.from;
        say "Godzilla: Found at $loc!";
        %match_locs{ $godzilla_rx } = $loc;

But using a regex object as a hash key evidently doesn't work,
it gives you the warning message:

   #  Regex object coerced to string (please use .gist or .perl to do that)

And what's worse is it coerces to an *empty list* which means *every*
regex is treated as the same key.

If you I follow the advice to use the *.perl, then that works, of course:

        %match_locs{ $godzilla_rx.perl } = $loc;

But you wouldn't be able to use the keys of the hash as a regex
object later, which seems sub-optimal, though not a concern for
my present purposes.

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About