in reply to Possible to use an expression as the hash key with exists?

The underlying structure doesn't permit this to be done without iterating over every key until the condition is matched.

If there's a possibility of multiple matches,

if ( $incomplete_isbn =~ m/^\d{5}$/ ) { my $re_key = qr/.+$incomplete_isbn.+/; my @matching_keys = grep /$re_key/, keys %$hashref_isbn; ... }

But it sounds like you want to check the same digits of the ISBN every time, and that those digits are unique. If so, then your hash is incorrectly keyed. It should be keyed by the partial ISBN. The full ISBN can be included as part of the value.

my %titles = ( partial_isbn => [ full_isbn, title ], partial_isbn => [ full_isbn, title ], partial_isbn => [ full_isbn, title ], partial_isbn => [ full_isbn, title ], );

By the way, qr/.+$incomplete_isbn.+/ doesn't seem to match what you specified, and can be simplified to qr/.$incomplete_isbn./.

By the way, $hashref_isbn is an aweful name. What does the hash contain, a list of titles? Then it should be called "titles" or "titles by isbn", not "isbn".

By the way, Tie::Hash::Regex does what you say you want, but I don't think it's a good solution to your problem.

Updated due to accidental post.

Replies are listed 'Best First'.
Re^2: Possible to use an expression as the hash key with exists?
by wenD (Beadle) on Sep 21, 2007 at 12:03 UTC
    I know what you mean about vague variable names. In this case $hashref_isbn holds everything from our isbn table so for me and colleagues the name does have meaning.

    Thanks for your idea about a hash keyed by partial ISBNs! Clever, clever.

    Here's what I ended up using:
    my @full_isbns = ( defined $hashref_isbn ? keys %{$hashref_isbn} : () +); my %isbn_by_stub = (); foreach my $full_isbn ( @full_isbns ) { my $stub_isbn = substr $full_isbn, 6, 5; $isbn_by_stub{$stub_isbn} = $isbn; } # 4-digit ISBN stub if ( $isbn =~ m/^\d{4}$/ ) { $isbn = 0 . $isbn; } # 5-digit ISBN stub if ( $isbn =~ m/^\d{5}$/ ) { if ( exists $isbn_by_stub{$isbn} ) { print "Found! $isbn matches $isbn_by_stub{$isbn}\n"; } }