I have a situation where I have an application and it maps to a directory I need to process in a zipfile. The mapping is quite simple:
CWA => "Financial",
PIP => "",
IFA => "IFA",
VDX => "Financial,
That is, if the name of the file begins with CWA
, I know the directory I have to munge is under Financial
. If the file name begins with a IFA
, I know the directory name is IFA
. I'd like to set this up as a hash (easy enough), but since these values don't really change, I'd like to setup this key => value mapping as a hash constant.
I don't believe this is possible, so I'd like to do the next best thing. What would that be? Or, can you setup a hash constant?
I'm thinking of writing a subroutine where you pass a parameter and it returns the correct value. After all, it's really the way constants themselves work, and it'd guarantee that the relationships between the keys and values don't change through out the program.
Or, I can simply declare the key => value relationship in the beginning of my program and hope that the key => value pairs aren't modified by something. This would be easier to read, and easier to modify if you have to since it's on the very top of my source code.
What's the best way to implement a key => value constant?
When a constant is used in an expression, Perl replaces it with its value at compile time, and may then optimize the expression further. In particular, any code in an if (CONSTANT) block will be optimized away if the constant is false.
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..
print "$ perl_print_hash_variable{'-hash_key2'} \n"; Description: The Perl print hash can used $ symbol for a single hash key and its value. The Perl print hash can use the % symbol for multiple hash keys and their values.
To add more elements to the Perl hash, just use that same syntax over and over, like this: $prices{'coke'} = 1.25; $prices{'sandwich'} = 3.00; (Note that there is no "Perl push" syntax for adding a new element to a Perl hash, but because people ask me that so many times, I wanted to make sure I mentioned it here.)
Alternativelly, if you don't want to use blocks you could still use constant:
use strict;
use warnings;
use constant CONSHASH => sub {{
foo1 => 'bar1',
foo2 => 'bar2',
foo3 => 'bar3',
}->{ +shift }};
print CONSHASH->('foo1') . "\n";
print CONSHASH->('foo2') . "\n";
print CONSHASH->('foo3') . "\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With