Perl是一种功能强大的编程语言,它的高级用法包括正则表达式、模块化、面向对象编程等。以下是一些Perl高级用法的案例:
my $string = "The price is $15 and the discount is $20.";
my @numbers = $string =~ /\d+/g;
print "@numbers\n"; # 输出 "15 20"
# my_module.pm
package MyModule;
use strict;
use warnings;
sub add {
my ($a, $b) = @_;
return $a + $b;
}
1;
然后,在主程序中使用该模块:
# main.pl
use strict;
use warnings;
use MyModule;
my $result = add(3, 4);
print "$result\n"; # 输出 "7"
# MyClass.pm
package MyClass;
use strict;
use warnings;
sub new {
my ($class, %params) = @_;
my $self = {
_name => $params->{name} || 'Unknown',
};
bless $self, $class;
return $self;
}
sub say_hello {
my ($self) = @_;
print "Hello, my name is $self->{_name}!\n";
}
1;
然后,在主程序中使用该类:
# main.pl
use strict;
use warnings;
use MyClass;
my $obj = MyClass->new(name => 'Alice');
$obj->say_hello(); # 输出 "Hello, my name is Alice!"
以上只是Perl高级用法的一些简单示例,Perl还支持许多其他高级特性,如异常处理、生成器、上下文感知等。