Perl是一種功能強(qiáng)大的編程語(yǔ)言,它的高級(jí)用法包括正則表達(dá)式、模塊化、面向?qū)ο缶幊痰取R韵率且恍㏄erl高級(jí)用法的案例:
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高級(jí)用法的一些簡(jiǎn)單示例,Perl還支持許多其他高級(jí)特性,如異常處理、生成器、上下文感知等。