LINUX CLASSES - PERL PROGRAMMING

Can You Explain Perl Variables to Me?

A variable in a Perl script is a means of referencing a numeric or character value. As in Bash scripts, Perl doesn't require you to declare a type for your variables. Perl figures out by context whether the value should be treated as a number or a character string and will even perform character-to-numeric value conversions when necessary. To assign or access the value (contents) of a variable, prefix it with a dollar sign. Spaces before or after the equal sign are optional, but if you want to assign a variable that contains character data, you must put quotation marks around the string.

$num=5;
$stuff = "chocolate truffles";
$user = $ENV{USER};

In these examples, Perl assigns 5 to the numeric variable $num, "chocolate truffles" to the variable $stuff, and the value of the USER environment variable to $user.

This is a good time to note that there are several distinct ways to use quotation marks in a Perl script. Let's look at the differences among single quotation marks, double quotation marks, backticks, and the backslash character and then follow up with some examples.

Single quotation marks, as in the preceding example, will always get you exactly what's inside the quotation marks--any characters that might otherwise have special meaning (like the dollar sign or the backslash) are treated literally.

Use double quotation marks when you want to assign a string that contains special characters that need to be interpreted.

The backslash is used to escape (treat literally) a single character (such as $ or *) that might otherwise be treated as a special character.

Use backticks to indicate that the string is a Linux command that should be executed, with the results assigned to a variable.

Now let's look at some examples that show when to use each method of quoting:

$user = $ENV{USER};
print 'Good Morning $user';

Yields: Good Morning $user

$user = $ENV{USER};
print "Good Morning $user";

Yields: Good Morning hermie

In the first case, the results would probably not be what you wanted. The single quotation marks caused Perl to not treat $user as a variable. In the second case, the results look much better. The double quotation marks allowed Perl to substitute the value of $user in the string.

Here's another example that demonstrates a common error:

$costmsg = "Price is $5.00";
print "$costmsg";
Yields
: Price is .00

We thought enough to quote the string, but the dollar sign tells Perl to use the value in the $5 variable, which is as yet undefined. We can easily solve the problem by prefixing the dollar sign with a backslash, as shown here:

$costmsg = "Price is \$5.00";
print "$costmsg";
Actual result: Price is $5.00

Finally, here's an example using backticks to execute a Linux command and capture the results in a Perl variable:

$currdir = `pwd`
print "Current directory is $currdir";
Yields: Current directory is /home/hermie

Previous Lesson: Perl Basics
Next Lesson: Perl Arguments

[ RETURN TO INDEX ]


   

Comments - most recent first
(Please feel free to answer questions posted by others!)

$umit     (14 Mar 2013, 11:10)
$longlis = `ls`;

In my script I tried to print the value of $longlis but it does not print anything. But when I try to print pwd or ls , it works fine.

Why does it behave like that ???
Tudor     (10 Feb 2013, 18:29)
Hi, thanks for sharing your experience. I think this is the suitable place to rise my question:

I try to check if my gateway's IP matches with a defined value. For this, I catch the IP into a variable using qx() then I run an if statement:
#!/usr/bin/perl

$a = qx(ip ro ls | grep default | cut -d ' ' -f3 );
print "a = ${a}\n";

$b = "123.456.789.111";
print "b = $b\n";
#$a = "123.456.789.111";

if ($a ne $b) { print "$a is different from $b\n"; }
print "Ok! they match\n";

It dont works! They are not identical even they "look" the same. There are still a perfect match: if I uncomment the second $a assignation.
However it is to be noticed that after getting the $a using qx(), it seems to be an extra "invisible" '\n' or other unprintable character that I don't know to get rid of... So, how do an expert proceed in this case?
Aruba     (17 Oct 2012, 16:23)
I have encountered problems with length of perl variables when trying to access ftp server.

e.g. perl contoftp.pl %website% %user% %password%

since these parameters can be very long...

Are there any restrictions with variables in one perl command?

If so, how can I bypass them?

thank you !
ravi     (22 Feb 2012, 06:41)
How cancate string ?
jannis Kafkoulas     (04 Jan 2012, 20:16)
Hi Bob,
Thanks very much for your quick answer.

I think, I didn't explain clearly enough what I mean:

I'm reading a logfile and I store the single field values in separate variables and these lot of variables I'm using to search/update/insert the whole entry in a mysql database.
And therefore I need to put the values in single quotes. So I don't have the literal value of the variable in order to escape the ' put the literal and again escape the '.

What I have ist rather this:

my $Query = "INSERT INTO $log_tbl (lognum, date, time, interf, orig, type, action, service, sport, src, dst, proto, rule, rulnam, crulenr, user, info, prod, hitcnt) VALUES ($logNr,$date,$time,$interf,$origin,$type,$action,$srvc_nam,$srcport,$src,$ dst,$proto,$fwrule,$rulename,$cruleNr,$user,$info,$prod,'1')";
Al VALUES-variables need to be surrounded by single quotes and I don't like do it this way:

$logNr = "'".$logNr."'"; and so on...


I think there should be a function putting the contents of a variable in single quotes like this:
func($a,$b,$c,...) but I can't remember it... :-(.

Bob Rankin     (04 Jan 2012, 12:56)
@Jannis - You must escape the single quotes with a backslash.

$a = "\'a\'";
jannis kafkoulas     (04 Jan 2012, 12:43)
Hi,

Just one simple question:
How can I get single quotes inside of varables,e.g.

I have: $a =a; $b = b; ...
and I'd like to have in $a 'a' (instead of just a),...

I don't like to make i manually like this:
$a = "'".$a."'";

Is there a simpler way?

Thanks very much

jannis
Bob Rankin     (24 May 2010, 08:57)
You have another minor problem. The $user variable will not be substituted because it's inside single quotes. Change to double quotes and it'll work. Also, no need to add the "\n" like you did. This will work the same:

print "Good Morning $user \n"
Dennis     (24 May 2010, 08:32)
I got already ;
print 'Good Morning $user',"\n"
Dennis     (24 May 2010, 08:27)
sorry i meaned \n, to invoke new line.
Dennis     (24 May 2010, 08:26)
print 'Good Morning $user';
Yields: Good Morning $user

How to insert here /n in order to be processed?
Bob Rankin     (03 May 2010, 14:09)
Quite right! Fixed now...
ben     (03 May 2010, 14:00)
I'm new to this, but isn't the second to last line supposed to read:
print "Current directory is $currdir";

I welcome your comments. However... I am puzzled by many people who say "Please send me the Linux tutorial." This website *is* your Linux Tutorial! Read everything here, learn all you can, ask questions if you like. But don't ask me to send what you already have. :-)

NO SPAM! If you post garbage, it will be deleted, and you will be banned.
*Name:
Email:
Notify me about new comments on this page
Hide my email
*Text:
 
 


Ask Bob Rankin - Free Tech Support


Copyright by - Privacy Policy
All rights reserved - Redistribution is allowed only with permission.

privacy policy