Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation for Perl syntax needed

Tags:

perl

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.

like image 222
Tah_Ra Avatar asked Jun 12 '26 09:06

Tah_Ra


1 Answers

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};
like image 173
brian d foy Avatar answered Jun 15 '26 07:06

brian d foy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!