Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re^5: Help with script recognizing variable in string

by Laurent_R (Canon)
on Jun 20, 2018 at 20:38 UTC ( [id://1217060]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Help with script recognizing variable in string
in thread Help with script recognizing variable in string

I guess I wasn't clear enough. There are two distinct points.

One is that scalar variables are interpolated (i.e. the variable is replaced by its value, for example when printing out the string) within a string if the string is initialized within double quotes, but not if the string is initialized within simple quotes. So the change that you did from single quotes to double quotes was a good move (although there are some limitations, as mentioned below by other monks).

my $var = "foo"; print 'Variable name is $var'; # prints: Variable name is $var print "Variable is $var"; # prints: Variable is foo
Then, even when the encompassing string is within double quotes, the compiler has to be able to know where the variable name ends to be able to interpolate the variable. It will be able to do so if the variable name is followed, for example, by a space or a punctuation symbol; but it might not be able to do it if the variable is followed by characters that are valid within an variable identifier, for example by some letters. In that case, a pair of curly brackets makes it possible to know where the variable name ends and the rest of the string starts, thereby removing any ambiguity. For example:
my $var = 10; print "There are $varapples"; # error: the compiler cannot know wh +ere the variable name ends print "There are $var apples"; # OK: the space after the variable m +akes it possible to know that the variable ends just there print "There are ${var}apples"; # prints: there are 10apples. # A space is missing, but the print +statement works, because the compiler can know # where the variable name ends thank +s to the curlies;

I hope this is clearer.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1217060]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-03-29 15:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found