📜  Perl-数据类型

📅  最后修改于: 2020-11-02 03:32:33             🧑  作者: Mango


Perl是一种松散类型的语言,在程序中使用时无需为数据指定类型。 Perl解释器将根据数据本身的上下文选择类型。

Perl具有三种基本数据类型:标量,标量数组和标量散列,也称为关联数组。这是有关这些数据类型的一些细节。

Sr.No. Types & Description
1

Scalar

Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters.

2

Arrays

Arrays are ordered lists of scalars that you access with a numeric index, which starts with 0. They are preceded by an “at” sign (@).

3

Hashes

Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%).

数字字面量

Perl在内部将所有数字存储为带符号整数或双精度浮点值。数字字面量以以下任何浮点或整数格式指定-

Type Value
Integer 1234
Negative integer -100
Floating point 2000
Scientific notation 16.12E14
Hexadecimal 0xffff
Octal 0577

字符串字面量

字符串是字符序列。它们通常是字母数字值,以单引号(’)或双引号(“)引起来。它们的工作方式与UNIX shell引号非常相似,您可以在其中使用单引号字符串和双引号字符串。

双引号字符串字面量允许变量插值,而单引号字符串则不允许。当某些字符以反斜杠开头时,它们具有特殊含义,并且用于表示换行符(\ n)或制表符(\ t)。

您可以将换行符或以下任何转义序列直接嵌入在双引号字符串-

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

让我们再次查看字符串在单引号和双引号中的行为。在这里,我们将使用上表中提到的字符串转义符,并将使用标量变量来分配字符串值。

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

这将产生以下结果-

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