Perl String Literals



Strings are sequences of characters. They are usually alphanumeric values delimited by either single (') or double (") quotes. They work much like UNIX shell quotes where you can use single-quoted strings and double-quoted strings.

Double-quoted string literals allow variable interpolation, and single-quoted strings are not. There are certain characters when they are proceeded by a backslash, have special meaning and they are used to represent like newline (\n) or tab (\t).

You can embed newlines 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 Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\0nn Creates Octal formatted numbers
\xnn Creates Hexideciamal formatted numbers
\cX Controls characters, x may be any character
\u Forces next character to uppercase
\l Forces next character to lowercase
\U Forces all following characters to uppercase
\L Forces 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 a single quotation and double quotation. Here we will use string escapes mentioned in the above table and will make use of the scalar variable to assign string values.

 Live Demo

#!/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";

Output

This will produce the 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
Updated on: 2019-11-28T07:58:55+05:30

772 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements