简体   繁体   English

Perl正则表达式不起作用

[英]Perl regular expression is not working

Hello I am trying to fetch couple of things using a Perl script. 您好我正在尝试使用Perl脚本获取一些东西。

my $fileName = "I_Payment_OK_2";
my ($msgType, $OfaCode, $msgCount) = $parseFileName;

#my $msgType = $parseFileName;
print $OfaCode;
print $msgType;
print $msgCount;

# parse the values from filename
sub  parseFileName {
     # parse the message type
     if($fileName =~ m/^(I|O)/) {
        $var1 = $1;
     }  
     # parse the OFAC trace keyword
     if($fileName =~ m/^[A-Z_][A-Za-z_]([A-Z]+)\w(\d+)$/) {
        $var2 = $2;
        $var3 = $3;
     }
     # return the message type & OFAC trace
     return ($var1, $var2, $var3);
     #return $var1; 
}

Nothing is getting printed. 什么都没有印刷。 Can anybody help me with this what is going wrong? 有人可以帮我解决这个问题吗?

Thanks 谢谢

You're never calling parseFileName(). 你永远不会调用parseFileName()。 Probably my ($msgType, $OfaCode, $msgCount) = $parseFileName; 可能是my ($msgType, $OfaCode, $msgCount) = $parseFileName; should be my ($msgType, $OfaCode, $msgCount) = parseFileName(); 应该是my ($msgType, $OfaCode, $msgCount) = parseFileName();

You should always use strict and use warnings at the start of your program, and declare all variables at the point of their first use using my . 你应该总是在程序开始时use strictuse warnings ,并在使用my的第一次使用时声明所有变量。 This applies especially when you are asking for help with your code as this measure can quickly reveal many simple mistakes. 这尤其适用于您在寻求代码帮助时,因为此措施可以快速揭示许多简单的错误。

From the look of your code it seems that you should be using split instead. 从代码的外观看,你应该使用split代替。

This program splits the file name string at the underscores, and extracts the first and the last two fields. 此程序将文件名字符串拆分为下划线,并提取第一个和最后两个字段。

use strict;
use warnings;

my $fileName = "I_Payment_OK_2";

my ($msgType, $OfaCode, $msgCount) = (split /_/, $fileName)[0, -2, -1];

print $msgType, "\n";
print $OfaCode, "\n";
print $msgCount, "\n";

output 产量

I
OK
2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM