avirup
avirup

Reputation: 1711

Perl regular expression is not working

Hello I am trying to fetch couple of things using a Perl script.

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

Upvotes: 0

Views: 987

Answers (2)

Borodin
Borodin

Reputation: 126742

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. 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.

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

Upvotes: 1

lanzz
lanzz

Reputation: 43178

You're never calling parseFileName(). Probably my ($msgType, $OfaCode, $msgCount) = $parseFileName; should be my ($msgType, $OfaCode, $msgCount) = parseFileName();

Upvotes: 1

Related Questions