user2498830
user2498830

Reputation: 17

Pattern Matching in perl

I want to parse some information from the file.

Information in the file:

Rita_bike_house_Sha9

Rita_bike_house

I want to have output like dis

$a = Rita_bike_house and $b = Sha9,

$a = Rita_bike_house and $b = "original"

In order to get that I have used the below code:

$name = @_; # This @_ has all the information from the file that I have shown above. 

#For matching pattern Rita_bike_house_Sha9 
($a, $b) = $name =~  /\w\d+/; 

if ($a ne "" and $b ne "" ) { return ($a,$b) } 
# this statement doesnot work at all as its first condition 
# before the end is not satisified. 

Is there any way where I can store "Rita_bike_house" in $a and "Sha9" in $b? I think my regexp is missing with something. Can you suggest anything?

Upvotes: 1

Views: 126

Answers (3)

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 3818

If you are sure that the pattern which is required will always be similar to 'Sha9' and also it will appear at the end then just do a greedy matching....

open FILE, "filename.txt" or die $!;
my @data = <FILE>;
close(<FILE>);
#my $line = "Rita_bike_house_Sha9";
foreach $line (@data)
{
    chomp($line);
    if ($line =~ m/(.*?)(_([a-zA-Z]+[0-9]+))?$/)
    {
        $a = $1;
        $b = $3 ? $3 : "original";
    }
}

Upvotes: 0

clt60
clt60

Reputation: 63902

Not very nice, but the next:

use strict;
use warnings;

while(<DATA>) {
    chomp;
    next if /^\s*$/;
    my @parts = split(/_/);
    my $b = pop @parts if $parts[$#parts] =~ /\d/;
    $b //= '"original"';
    my $a = join('_', @parts);
    print "\$a = $a and \$b = $b,\n";
}

__DATA__
Rita_bike_house_Sha9
Rita_bike_house

prints:

$a = Rita_bike_house and $b = Sha9,
$a = Rita_bike_house and $b = "original",

Upvotes: 0

shawnhcorey
shawnhcorey

Reputation: 3601

Please don't use the variables $a and $b in your code. There are used by sort and will confuse you.

Try:

while( my $line = <DATA> ){
  chomp $line;

  if( $line =~ m{ \A ( \w+ ) _ ( [^_]* \d [^_]* ) \z }msx ){
    my $first = $1;
    my $second = $2;
    print "\$a = $first and \$b = $second\n";
  }else{
    print "\$a = $line and \$b = \"original\"\n";
  }
}

__DATA__
Rita_bike_house_Sha9
Rita_bike_house

Upvotes: 2

Related Questions