Learning Perl: 9.4. m// in List Context

Previous Page
Next Page

 

9.4. m// in List Context

When you use split, the pattern specifies the separator: the part that isn't the useful data. Sometimes it's easier to specify what you want to keep.

When a pattern match (m//) is used in a list context, the return value is a list of the memory variables created in the match or an empty list if the match failed:

    $_ = "Hello there, neighbor!";
    my($first, $second, $third) = /(/S+) (/S+), (/S+)/;
    print "$second is my $third/n";

This makes it easy to give the match variables easy-to-use names, and these names may persist past the next pattern match. (Because there's no =~ in that code, the pattern matches against $_ by default.)

The /g modifier you first saw on s/// also works with m//, which lets it match at more than one place in a string. In this case, a pattern with a pair of parentheses will return a memory from each time it matches:

    my $text = "Fred dropped a 5 ton granite block on Mr. Slate";
    my @words = ($text =~ /([a-z]+)/ig);
    print "Result: @words/n";
    # Result: Fred dropped a ton granite block on Mr Slate

This is like using split inside out. Instead of specifying what we want to remove, we specify what we want to keep.

If there are more than one pair of parentheses, each match may return more than one string. Let's say we have a string we want to read into a hash, like this:

    my $data = "Barney Rubble Fred Flintstone Wilma Flintstone";
    my %last_name = ($data =~ /(/w+)/s+(/w+)/g);

Each time the pattern matches, it returns a pair of memories. Those pairs of values become the key/value pairs in the newly created hash.

Previous Page
Next Page
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值