Nikhil Hegde
Nikhil Hegde

Reputation: 341

Not sure of the reason for output value

I have these two statements in a perl code that I'm trying to understand.

our $CSITOOLS=`/x/eng/csitools/netapp_menu/common/csitools.sh`;
print "${CSITOOLS}\n";

Output:

/x/eng/csitools

How does ${VARIABLE_NAME} work? (In this case {CSITOOLS})

Thanks!

Upvotes: 0

Views: 64

Answers (3)

PerlDuck
PerlDuck

Reputation: 5720

From perldata:

As in some shells, you can enclose the variable name in braces to disambiguate it from following alphanumerics (and underscores).

That is:

If you have a variable like $foo and you want to interpolate that whithin a string:

my $string = "This is $foobar";

then Perl would look for the variable $foobar. To make clear your variable's name is just $foo you need to write

my $string = "This is ${foo}bar";

This is the way to delimit the variable's name. In your particular case the curlies {} aren't needed because "$CSITOOLS\n" already is unambiguous. However, it does no harm.

Upvotes: 5

stevieb
stevieb

Reputation: 9296

Perl allows you to surround the name of a scalar variable with braces ({}) to separate its name from any surrounding characters. Imagine you have the word "item" in a variable, and you want to print item99 within a string, with no whitespace in between:

my $name = "item";
print "${name}99\n";

Without the braces, perl would interpret the variable like this:

print "$name99\n";

...which is an undeclared, undefined variable, and definitely not what you mean. With warnings enabled, would display something like:

Use of uninitialized variable in ...

If warnings are not enabled, the program may merrily run along and do other things, possibly/likely breaking something far down the line. That makes things really difficult to troubleshoot.

In your simple case, the braces aren't needed, and you don't see them all that very often in print statements, unless you need to combine variables where there's no whitespace character between it and other valid variable characters when interpolating within a string.

Upvotes: 3

Nicholas Jones
Nicholas Jones

Reputation: 63

From perldoc.perl.org

A string enclosed by backticks (grave accents) first undergoes double-quote interpolation. It is then interpreted as an external command, and the output of that command is the value of the backtick string, like in a shell.

Apparently, the result of csitools.sh is the string /x/eng/csitools

Upvotes: 2

Related Questions