l*****n 发帖数: 72 | 1 I get a very subtle question about regular expression in Perl.
for example, I have a data.txt like below:
440|34|56
44|33|56
441|23|56
442|31|56
443|30|56
0440|74|56
1441|53|56
2442|84|56
3443|92|56
The first field is the ID number.
for example, I need to find a line start exactly with ID=44, to avoid
finding some ID 440, 441, ... etc. I need to put delimiter "|" after the
ID. i.e., I am looking for a line starting with ID, and also ID
followed by delimiter "|".
1: $trackData = "data.txt";
2: open(IFILE, $trackData) or die "Can't open $trackData :
$!";
3: while($trackLine =)
4: { $_=$trackLine;
5: $ID="44"; $ID_pipe=$ID."|";
6: if(/^($ID_pipe)/) {print $trackLine; }
7: }
8: close(IFILE);
Now the problem is coming. (variable for pattern match)
http://www.gossland.com/course/matching/advanced.html
You can use variables for the pattern match quite freely, but keep in
mind they really do act as search patterns, not as defined strings. For
instance if your variable was
$match = "yes?"
then
$question =~ /$match/
would specify a search like /yes?/ and you'd be looking for "ye"
followed by 0 or 1 occurences of s, not the literal string ""yes?" with
a question mark.
Since I used a "|" in the match patter, which treat "|" as logical OR
operation instead of "|". | b******n 发帖数: 592 | 2 use awk '$1=44{print $0;}' | l*****n 发帖数: 72 | 3
没错!这是最直接了当的方法。 :)
但是我用 Perl 的原因就是这只是整个Program中的一部分,由于牵涉到几层循环,不
能在
AWK 操作里面再做 AWK 操作,所以转向了 Perl。
否则的话无论 AWK或者 Shell 都有很简单的解决办法。
多谢了!
【在 b******n 的大作中提到】 : use awk '$1=44{print $0;}'
| b******n 发帖数: 592 | 4 escape in string "\\|"
【在 l*****n 的大作中提到】 : : 没错!这是最直接了当的方法。 :) : 但是我用 Perl 的原因就是这只是整个Program中的一部分,由于牵涉到几层循环,不 : 能在 : AWK 操作里面再做 AWK 操作,所以转向了 Perl。 : 否则的话无论 AWK或者 Shell 都有很简单的解决办法。 : 多谢了!
| l*****n 发帖数: 72 | 5
Man, you are genius!
Small piece of code saved a big slot of time!!
Many thanks!
【在 b******n 的大作中提到】 : escape in string "\\|"
| b******n 发帖数: 592 | 6 如果你不把"\|"放在变量里面,而是直接放在match block: /$var\|/方便很多。。。
【在 l*****n 的大作中提到】 : : Man, you are genius! : Small piece of code saved a big slot of time!! : Many thanks!
| l*****n 发帖数: 72 | 7
Oh,Yeah!
I did not realize that.
Thanks a lot!
【在 b******n 的大作中提到】 : 如果你不把"\|"放在变量里面,而是直接放在match block: /$var\|/方便很多。。。
|
|