Perl 小知识之多行匹配

如果想匹配多行文本(即文本中有换行符)中的内容,比如:

1 aaa
2 
3 ...
4 
5 bbb
6 
7 ...

要匹配aaa和bbb之间的内容,我们可以使用 /aaa.*bbb/s

其中/s修饰符可以让.匹配任何字符,包括换行符。

不过,除此之外,我们可以使用..操作符:

/aaa..bbb/

就像sed命令一样:sed -n '/aaa/,/bbb/p' file

..操作符叫做区块运算符(Range Operator) ,这个运算符是 Perl 语言中特有的运算符,是一个很实用的运算符.  

比如: 

1 @digits=(1..9); #此时 @digits=(1,2,3,4,5,6,7,8,9);    
2 @digits=('01'..'05'); #此时 @digits=(01,02,03,04,05);    
3 @char=('A'..'E'); #此时 @char('A','B','C','D','E',);    
4 @total=(1..3'A'..'B'); #此时 @total=(1,2,3'A','B');

摘抄一段解释:

In scalar context, ".." returns a boolean value.  The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and various editors.  Each ".." operator maintains its own boolean state.  It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, AFTER which the range operator becomes false again.  It doesn't become false till the next time the range operator is evaluated.  It can test the right operand and become false on the same evaluation it became true (as in awk), but it still returns true once.  If you don't want it to test the right operand till the next evaluation, as in sed, just use three dots ("...") instead of two.  In all other regards, "..." behaves just like ".." does.

即..和...的差别在于:当一个..flip-flop为true时,它会返回true,同时测试它的右侧表达式以决定是否需要将其内部状态设置回false;而对于...flip-flop来说,它等到下一次求值的时候才测试其右侧表达式。观察下面的代码:

1 (1..10).each {|x| print x if x==3..x>=3}
2 # Prints "3"  .  Flips and flops back  when x==3
3 
4 (1..10).each {|x| print x if x==3...x>=3}
5 # Print "34" .   Flis when x==3 and flops when x==4

 

转载于:https://www.cnblogs.com/yuyan/p/3168653.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值