Tuesday, 11 March 2014

Escaping characters and Literals



Escaping Characters

Perl uses the backslash (\) character to escape any type of character that might interfere with our code. Let's take one example where we want to print double quote and $ sign:
#!/usr/bin/perl
$result = "This is \"number\"";
print "$result\n";
print "\$result\n";
This will produce following result:
This is "number"
$result

Numeric Literals

Perl stores all the numbers internally as either signed integers or double-precision floating-point values. Numeric literals are specified in any of the following floating-point or integer formats:
Type
Value
Integer
1234
Negative integer
-100
Floating point
2000
Scientific notation
16.12E14
Hexadecimal
0xffff
Octal
0577

String Literals

Strings are sequences of characters. They are usually alphanumeric values delimited by either single (') or double (") quotes.
Double-quoted string literals allow variable interpolation, and single-quoted strings are not. There are certain characters when they are preceded by a back slash they will have special meaning and they are used to represent like new line (\n) or tab (\t).
You can embed new lines or any of the following Escape sequences directly in your double quoted strings:
Escape sequence
Meaning
\\
Backslash
\'
Single quote
\"
Double quote
\a
Alert or bell
\b
Backspace
\f
Form feed
\n
New line
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\0nn
Creates Octal formatted numbers
\xnn
Creates Hexadecimal formatted numbers
\cX
Control characters, x may be any character
\u
Force next character to uppercase
\l
Force next character to lowercase
\U
Force all following characters to uppercase
\L
Force all following characters to lowercase
\Q
Backslash all following non-alphanumeric characters
\E
End \U, \L, or \Q

Example

Let's see again how strings behave with single quotation and double quotation. Here we will use string escapes mentioned in the above table and will make use of scalar variable to assign string values.
#! /usr/bin/perl
# This is case of interpolation.
$str = "Welcome to \ntutorialspoint.com!";
print "$str\n";
 
# This is case of non-interpolation.
$str = 'Welcome to \ntutorialspoint.com!';
print "$str\n";
 
# Only W will become upper case.
$str = "\uwelcome to tutorialspoint.com!";
print "$str\n";
 
# Whole line will become capital.
$str = "\UWelcome to tutorialspoint.com!";
print "$str\n";
 
# A portion of line will become capital.
$str = "Welcome to \Ututorialspoint\E.com!"; 
print "$str\n";
 
# Backsalash non alpha-numeric including spaces.
$str = "\QWelcome to tutorialspoint's family";
print "$str\n";
This will produce following result:
Welcome to
tutorialspoint.com!
Welcome to \ntutorialspoint.com!
Welcome to tutorialspoint.com!
WELCOME TO TUTORIALSPOINT.COM!
Welcome to TUTORIALSPOINT.com!
Welcome\ to\ tutorialspoint\'s\ family

No comments: