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還支持許多其他高級特性,如異常處理、生成器、上下文感知等。