Search code examples
perlvariablessymbolic-references

How can I use a variable's value as a Perl variable name?


Sorry about all these silly questions, I've been thrust into Perl programming and I'm finding it really hard to think like a Perl programmer.

Silly question for today: I load a pipe delimited file into a hash using the id field as the key, like so

#open file

my %hash;
while (<MY_FILE>) {
    chomp;

    my ($id, $path, $date) = split /\|/;

    $hash{$id} = {
        "path" => $path,
        "date" => $date
    };
}

There a few times, however, when I actually need the key to be the path because, for whatever reason (and no, it can't be changed) the id isn't unique, so I had the bright idea that I could put it all into a subroutine and pass the name of the variable to use as the key to it, kinda like so:

load_hash("path");

sub load_hash {
    my $key = shift;

    #do stuff, and then in while loop
    $hash{${$key}} = #and so on
}

but in perldb x ${$key} is always undef, although x ${path} prints the value in $path.

Is there some way of doing what I'm trying to?

TIA


Solution

  • Something like this?

    use Carp 'confess';
    
    sub load_hash {
        my $key = shift;
    
        # ...
    
        while (...) {
            # ...
            my %line;  # important that this is *inside* the loop
            @line{qw (id path date)} = split /\|/;
            confess "BUG: unknown key '$key'"  unless exists $line{$key};  # error checking
            $hash{$line{$key}} = \%line;
            delete $line{$key};  # assuming you don't want the key value duplicated
        }
    }