Home > Back-end >  Explanation for Perl syntax needed
Explanation for Perl syntax needed

Time:08-16

I have a line in a code something like that:

my $thefilename  = ${'myConfig::connection' . $argument}{thefilename};

the thefilename is passed through another file. Can someone elaborate what does 'myConfig::connection' part means? and what does that ${}{}; part mean?

This is legacy code and I am pretty much new to Perl.

CodePudding user response:

The code is constructing a variable name for a hash, then making a single element reference to a hash. This is called a "soft reference", and something that's typically frowned upon nowadays because there are better ways to accomplish that.

A single element access to a hash looks like this, where the hash variable has already been defined (or maybe not defined yet in the absence of strict):

my %hash_name;
$hash_name{$key}

There a syntax for dereferencing a hash reference where you surround the reference in braces then access the key you want. This is the tedious old "circumfix" notation:

my $ref = { a => 1, ... };
${ $ref }{$key};

If that value in $ref is not a reference, Perl can use the simple string value in that variable as the variable name. This is a soft reference (and one of the things disallowed by use strict):

my $ref = 'hash_name';
${ $ref }{$key};

You don't want to do this unless you know what you are doing, which is why strict warns you about it.

But you can put the string directly in the braces and skip the variable:

${ 'hash_name' }{$key}

Or construct the string inside the braces:

${ 'hash' . '_' . 'name' }{$key}

In your case, you end up with:

${'myConfig::connection' . $argument}{thefilename};
  •  Tags:  
  • perl
  • Related