Skip to content

Perl 变量

Perl - Modern Perl 中的变量 (Variables)

Section titled “Perl - Modern Perl 中的变量 (Variables)”

变量是内存中命名的存储位置。在 Perl 中,变量可以容纳的数据类型由其“sigil”——一个位于变量名称开头的特殊字符——指示。

现代 Perl 编程强烈倡导使用 use strict; 和 use warnings;。启用 use strict; 后,变量在使用前必须先声明,通常使用 my 关键字,这会赋予它们词法作用域 (lexical scope),使其作用范围限定在封闭的代码块、文件或 eval 中。

Perl 内建了三种主要的数据类型,每种都有对应的变量类型:

  • 标量 (Scalars) ($): 容纳单个值,如数字、字符串或引用 (reference)。
  • 数组 (Arrays) (@): 容纳一个有序的标量列表。
  • 哈希 (Hashes) (%): 容纳一个无序的键值对集合(关联数组)。

Perl 为不同的变量类型维护独立的命名空间。这意味着 $name、@name 和 %name 是不同的变量。

当 use strict; 生效时,你必须使用 my(用于词法作用域变量)、our(用于包变量,也是词法作用域)或 state(用于持久性词法变量,Perl 5.10+)来声明变量。最常用的是 my。

等号 (=) 用于赋值。

my $age = 30; # Scalar: integer assignment
my $name = "Jane Doe"; # Scalar: string assignment
my $pi = 3.14159; # Scalar: floating-point number
my @colors = ("red", "green", "blue"); # Array of strings
my %capitals = ( # Hash: key => value pairs
"USA" => "Washington D.C.",
"France" => "Paris",
);

标量变量容纳单个数据。这可以是一个数字(整数或浮点数)、一个字符串,或者一个引用(指向另一个数据结构)。

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my $count = 10;
my $message = "Processing complete.";
my $temperature = 25.5;
say "Count: $count";
say "Message: $message";
say "Temperature: $temperature C";

输出 (Output):

Count: 10
Message: Processing complete.
Temperature: 25.5 C

数组变量存储一个有序的标量值列表。数组索引从 0 开始。

要访问数组的单个元素,使用 $ sigil 和数组名称,后跟方括号中的索引(例如,$array_name[0])。

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my @fruits = ("apple", "banana", "cherry");
say "First fruit: $fruits[0]"; # Accessing the first element
say "Second fruit: $fruits[1]";
$fruits[2] = "mango"; # Modifying an element
say "All fruits: @fruits"; # Interpolates the array with spaces
my $num_fruits = @fruits; # In scalar context, an array returns its size
say "Number of fruits: $num_fruits";

输出 (Output):

First fruit: apple
Second fruit: banana
All fruits: apple banana mango
Number of fruits: 3

常用的数组操作包括 push(添加到末尾)、pop(从末尾移除)、shift(从开头移除)和 unshift(添加到开头)。

哈希变量存储键值对的集合。键 (keys) 是唯一的字符串,值 (values) 是标量。哈希是无序的(尽管最近的 Perl 版本在迭代时提供了一些顺序一致性,但不应依赖此进行程序逻辑)。

要访问哈希的单个元素,使用 $ sigil 和哈希名称,后跟花括号中的键(例如,$hash_name{key})。在定义哈希时,通常使用“胖逗号”(=>) 来提高可读性。

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my %ages = (
"Alice" => 30,
"Bob" => 24,
"Carol" => 42,
);
say "Alice's age: $ages{Alice}";
$ages{David} = 19; # Adding a new key-value pair
# Iterating through a hash
say "Known ages:";
foreach my $name (keys %ages) { # 'keys %ages' returns a list of all keys
say " $name is $ages{$name} years old.";
}

输出 (Output,迭代顺序可能不同):

Alice's age: 30
Known ages:
Carol is 42 years old.
David is 19 years old.
Alice is 30 years old.
Bob is 24 years old.

Perl 根据变量或表达式所在的“上下文 (context)”来确定如何解释它。两个主要的上下文是标量上下文 (scalar context) 和列表上下文 (list context)。

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
my @elements = ('A', 'B', 'C');
# List context: assigning to an array copies elements
my @copy_of_elements = @elements;
say "Copy: @copy_of_elements"; # Output: Copy: A B C
# Scalar context: assigning to a scalar gives the number of elements
my $count_of_elements = @elements;
say "Count: $count_of_elements"; # Output: Count: 3
# String context (a type of scalar context)
my $string_representation = "@elements";
say "String: $string_representation"; # Output: String: A B C (elements joined by space)

理解上下文对于编写正确的 Perl 代码至关重要。其他上下文包括布尔上下文 (boolean, 真/假判断) 和空上下文 (void, 值被丢弃)。

为了进一步学习,请探索引用 (references),它可以创建复杂的嵌套数据结构,如哈希数组或数组哈希。此外,还可以探索 Perl 的面向对象特性以应用于大型应用程序。