in reply to Check if key exist in hash but not exact match
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use experimental qw( signatures ); sub trie_exists($trie, $key) { my $ref = $trie; for my $char (split //, $key) { return unless exists $ref->{$char}; $ref = $ref->{$char}; } return 1 } my %prices = (pizza => 12, coke => 1.25, sandwich => 3); my %trie; for my $key (keys %prices) { my @chars = split //, $key; my $ref = \%trie; for my $char (@chars[0 .. $#chars - 1]) { $ref->{$char} //= {}; $ref = $ref->{$char}; } $ref->{ $chars[-1] } = $prices{$key}; } if (trie_exists(\%trie, 'cok')) { say "found the preifx 'cok' in the hash"; } die 'Full key' unless trie_exists(\%trie, 'pizza'); die 'Non prefix' if trie_exists(\%trie, 'andwich');
There are also several trie modules on CPAN, but I haven't tried any of them, so can't make a recommendation.
|
|---|