Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl encapsulate single variable in double quotes

In Perl, is there any reason to encapsulate a single variable in double quotes (no concatenation) ?

I often find this in the source of the program I am working on (writen 10 years ago by people that don't work here anymore):

my $sql_host = "something";
my $sql_user = "somethingelse";

# a few lines down
my $db = sub_for_sql_conection("$sql_host", "$sql_user", "$sql_pass", "$sql_db");

As far as I know there is no reason to do this. When I work in an old script I usualy remove the quotes so my editor colors them as variables not as strings.

I think they saw this somewhere and copied the style without understanding why it is so. Am I missing something ?

Thank you.

like image 707
Radu Maris Avatar asked Feb 06 '12 09:02

Radu Maris


2 Answers

All this does is explicitly stringify the variables. In 99.9% of cases, it is a newbie error of some sort.

There are things that may happen as a side effect of this calling style:

my $foo = "1234";
sub bar { $_[0] =~ s/2/two/ }
print "Foo is $foo\n";
bar( "$foo" );
print "Foo is $foo\n";
bar( $foo );
print "Foo is $foo\n";

Here, stringification created a copy and passed that to the subroutine, circumventing Perl's pass by reference semantics. It's generally considered to be bad manners to munge calling variables, so you are probably okay.

You can also stringify an object or other value here. For example, undef stringifies to the empty string. Objects may specify arbitrary code to run when stringified. It is possible to have dual valued scalars that have distinct numerical and string values. This is a way to specify that you want the string form.

There is also one deep spooky thing that could be going on. If you are working with XS code that looks at the flags that are set on scalar arguments to a function, stringifying the scalar is a straight forward way to say to perl, "Make me a nice clean new string value" with only stringy flags and no numeric flags.

I am sure there are other odd exceptions to the 99.9% rule. These are a few. Before removing the quotes, take a second to check for weird crap like this. If you do happen upon a legit usage, please add a comment that identifies the quotes as a workable kludge, and give their reason for existence.

like image 153
daotoad Avatar answered Sep 28 '22 11:09

daotoad


In this case the double quotes are unnecessary. Moreover, using them is inefficient as this causes the original strings to be copied.

However, sometimes you may want to use this style to "stringify" an object. For example, URI ojects support stringification:

my $uri = URI->new("http://www.perl.com");
my $str = "$uri";
like image 38
Eugene Yarmash Avatar answered Sep 28 '22 13:09

Eugene Yarmash