作者liyih ()
看板Perl
标题Re: [问题] 关於搜寻字串
时间Mon Nov 8 11:46:01 2010
※ 引述《n1lk5g2 (不决定习惯自由)》之铭言:
: 标题: [问题] 关於搜寻字串
: 时间: Sat Nov 6 17:25:55 2010
:
: 下面是我自己写的一个程式
:
: my $input = shift;
:
: my $string = "你好吗";
:
: if ($string =~ /$input/) {
:
: print "有在其中\n";
: }else{
:
: print "没有\n";
: }
:
: 但遇到一个小bug
:
: 就是如果输入的是空格 依然会显示"有在其中"
:
: 想问一下问题出在哪
:
: 谢谢
请记得开启
use strict;
use warnings;
my $pattern = undef;
if ("test_string" =~ m/$pattern/) {
print "match\n";
}
Use of uninitialized value $pattern in regexp compilation at ...
:
: --
:
※ 发信站: 批踢踢实业坊(ptt.cc)
: ◆ From: 140.114.217.81
: 推 rkcity:检查一下你$input 猜测是你没有正确读入"空白字元" 11/06 20:25
: → n1lk5g2:不懂大大意思 请问是? 11/07 00:37
: → rkcity:$input的内容真的是'空白字元'吗? 11/07 04:38
: → rkcity:command line可以传空白字元当引数吗._.? 可以的话我也想学 11/07 18:11
# ./test.pl " " 1 2 3
用引号括住应该就可以传入空白字元
: → rkcity:改用$input = <STDIN>让使用者输入吧 11/07 18:12
: → rkcity:你应该还需要用到chomp把input後面的换行字元去掉 11/07 18:13
: ※ 编辑: n1lk5g2 来自: 140.114.217.81 (11/07 21:31)
: → n1lk5g2:那我chomp应该怎麽用呢? 抱歉我是新手 看着书学的... 11/07 21:31
: → n1lk5g2:很不会perl...只有按照书上写出排数字大小的程式而已 11/07 21:32
: → drm343:chomp($input = <STDIN>); 11/07 21:55
: → drm343:其实我也想知道为什麽 shift 会导致 if 为真 11/07 22:01
: → drm343:另一个解决 bug 的方法是在比对之前,先比对 $input,这样 11/07 22:08
: → drm343:就不需要改变 shift 的输入方式, 11/07 22:08
: → drm343:if ( $input eq "" ){exit;} 11/07 22:08
my $input = shift;
应该就是 shift 出 @ARGV,也就是 $ARGV[0]
根据上面推断,没有带参数,但 shift,所以 $input 是 undef,
而用 undef 去做 regexp 比对会是 match!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.114.64.130
※ 编辑: liyih 来自: 140.114.64.130 (11/08 11:46)
1F:推 rkcity:喔喔! 原来我用错引号了 单引号会被当成字元读入._." 11/08 13:45
2F:→ liyih:单引号或是双引号应该是和 shell 有关... 11/08 14:23
3F:推 n1lk5g2:所我我的程式码应该怎麽改写呢 有点不知道问题出在哪 11/08 16:57
4F:→ n1lk5g2:抱歉我刚学perl不久 很多东西都不懂 麻烦各位大大了 11/08 16:57
5F:推 drm343:感谢!第一次知道 undef 的 regexp 会是 match! 11/08 19:52