Perl中模式匹配後,返回的子字串可存儲在標量、列表、哈希中

舉例說明:

1. 標量:

    匹配成功返回1,匹配失敗返回0;

my $res = ($string=~/value='(\w+)'/);
print "$res\n";

output:

1


2. 列表:

use Data::Dumper;
my $string = "hello perl";
my @perls = $string =~ m/hello/ig ;
print Dumper @perls;

output:

$VAR1 = 'hello';


$string = "name='ns' value='CSDN'";
my ($res) = ($string=~/value='(\w+)'/);
print "$res\n";

output:

CSDN



3. 哈希:

$string = "name=xxyy leval=9 score=0";
%hash = {leval=>"12"};
%hash = $string =~ /(\w+)=(\w+)/g;
print Dumper(\%hash);   #先按照列表匹配獲得值,然後再通過列表對hash賦值


output:

$VAR1 = {
          'name' => 'xxyy',
          'level' => '9', (修改了hash裏面原來的password的值)
          'score' => '0'
        };

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章