perl 中的无限循环 [英] Infinite while-loop in perl

查看:73
本文介绍了perl 中的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做到这一点而不会陷入无限循环?

while((my $var) = $string =~/regexline(.+?)end/g) {打印 $var;}

这会导致无限循环,可能是因为直接从 while 中的正则表达式分配 var 每次都返回true"?

我知道我可以做到:

while($string =~/regexline(.+?)end/g) {我的 $var = $1;打印 $var;}

但我希望我能保存一行.是否有我可以使用的正则表达式修饰符或类似的东西?

(另外,这个符号/技巧实际上叫什么,如果我想搜索它:

(my $var) = $string =~/regex/;

谢谢!!

解决方案

有没有办法做到这一点而不会陷入无限循环?

是的.使用 foreach() 而不是 while() 循环:

foreach my $var ($string =~/regexline(.+?)end/g) {

<块引用>

这个符号/技巧实际上叫什么,如果我想搜索它

它在列表上下文中被称为匹配.它在perldoc perlop"中有描述:

<块引用>

g 修饰符指定全局模式匹配——即在字符串内匹配尽可能多的次数.它的行为取决于上下文.在列表上下文中...

Is there a way to do this without getting an infinite loop?

while((my $var) = $string =~ /regexline(.+?)end/g) {
    print $var;
}

This results in an infinite loop, probably because the assigning of a var directly from a regex inside the while returns "true" every time?

I know I can do this:

while($string =~ /regexline(.+?)end/g) {
     my $var = $1;      
     print $var;
}

But I was hoping I could save a line. Is there a regex modifier I can use or something like that?

(Also, what is this notation/trick actually called, if I want to search for it:

(my $var) = $string =~ /regex/;

Thanks!!

解决方案

Is there a way to do this without getting an infinite loop?

Yes. Use a foreach() instead of a while() loop:

foreach my $var ($string =~ /regexline(.+?)end/g) {

what is this notation/trick actually called, if I want to search for it

It is called a match in list context. It is described in "perldoc perlop":

The g modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context ...

这篇关于perl 中的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆