Need help with Perl

Dear friends,
I am trying to separate records from a file, search a pattern and print the record having the pattern. I was able to come up with the following code:

#/bin/perl
$a="
<L:RECORD>name=fai far,age=21,
company=Company ABC,project=BT App
</L:RECORD>
<L:RECORD>name=abc xyz,age=22,company=Inf Typ Tech,project=AT</L:RECORD>
<L:RECORD>name=uresh kum,
age=20,company=TC LTD,project=VGP</L:RECORD>
<L:RECORD>name=mah laxmi,age=23,company=Tata Co,project=JP MS</L:RECORD>
";
@a=split(/L:RECORD\>/,$a);
print "Enter Search Pattern: ";
$searchPattern=<>;
chomp($searchPattern);
foreach $i (@a) {
    if($i=~m/$searchPattern/) {
    print "$i\n";
    }
}

This works perfectly fine, but as you can see, the input is hardcoded($a). Now supposing I want to read the same input from a file and come up with the same results as the above script, how do I do it? I have tried using some filehandling, but unable to succeed :(. Anyone help out please!!
Thanks in advance for the help :slight_smile:

Not sure, what went wrong with your appraoch.

Read the file that contains the pattern to be used for split up,
read the entire file to an array
join it with required delimiter

Hiii,
Thing is, I am new to file handles. This is what I tried:

print "Enter Search pattern: ";
$user_input=<>;
chomp($user_input);
open (LOGFILE, "perl_try_ip.txt");
$input=<LOGFILE>;
@input=split(/L:RECORD\>/,$input);
for $line (@input)#(<LOGFILE>)
{
    if($line=~m/$user_input/)
    {
        print $line;
    }
}
close LOGFILE;

Does not seem to be working :frowning:

You have to read the entire file content and have it in a variable.
Try with this code...

print "Enter Search pattern: ";
$user_input=<>;
$/="";
chomp($user_input);
open (LOGFILE, "file");
$input=<LOGFILE>;
@input=split(/L:RECORD\>/,$input);

for $line (@input)#(<LOGFILE>)
{
    if($line=~m/$user_input/)
    {
        print $line;
    }
}
close LOGFILE;

You could try something like this:

#! /usr/bin/env perl

use warnings;
use strict;

my $logfile = 'perl_try_ip.txt';

open LOGFH, '<', $logfile or die "$logfile: $!\n";
my $tag = qr(</?L:RECORD>);
undef $/;
my @content = split $tag, <LOGFH>;
close LOGFH or warn "$logfile: $!\n";
$/ = "\n";

while (1) {
    print "Enter Search pattern: ";
    chomp( my $user_input = <STDIN> );
    last unless $user_input or $user_input =~ /exit|quit/;
    my @matches = grep /$user_input/, @content;
    print @matches ? join "\n", @matches : 'no match', "\n";
}

Hey Guys, Both the above codes are working perfect. Thanks a lot for the help guys :slight_smile:

This should be safer, pushing $/ manipulation to a block

open LOGFH, '<', $logfile or die "$logfile: $!\n";
my $tag = qr(</?L:RECORD>);
my @content;
{
undef $/;
@content = split $tag, <LOGFH>;
}
close LOGFH or warn "$logfile: $!\n";

Yep,
thanks for pointing it out.

Hey Friends,

Just for info, what's "$/" for? :confused:

Input record delimiter. ($/)
Its newline by default.