Learning Perl: 9.4. m// in List Context
来源:互联网 发布:添加打印机无usb端口 编辑:程序博客网 时间:2024/06/10 09:39
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.
- Learning Perl: 9.4. m// in List Context
- Learning Perl: 3.8. in List Context
- Learning Perl: 3.7. Scalar and List Context
- scalar and list context in Perl
- Thinking in Perl Learning
- Learning Perl: 3.3. List Literals
- Learning Perl: 3.4. List Assignment
- Perl Learning 2 List&Array
- Learning Perl: 8.1. Matches with m//
- List and Array in Perl
- Learning Perl: 4.5. Private Variables in Subroutines
- Learning Perl: 2.3. Perl's Built-in Warnings
- Adding custom context menu in classical list
- Learning Perl
- Learning Perl
- Learning Perl
- Learning Perl:
- Learning Perl
- C/C++中关于地址、指针和引用变量的学习笔记(十) : 引用型变量
- Learning Perl: 9.2. The split Operator
- PHP中双引号和单引号的区别和用法
- 10.10 信号_alarm和pause函数
- Learning Perl: 9.3. The join Function
- Learning Perl: 9.4. m// in List Context
- 瑞斯康达NView 5 研究实录 (6) - 功能实现二
- java Script查询列表排序
- Learning Perl: 9.5. More Powerful Regular Expressions
- Learning Perl: 10.1. The unless Control Structure
- 重置cdr的billsec的方法
- 飞秋_飞秋2010_飞秋2010下载_飞秋下载2010正式版
- Learning Perl: 10.2. The until Control Structure
- Learning Perl: 10.3. Expression Modifiers