Search code examples
perl

How to store selected information in array?


I have 1 file to read.

file1.txt contains:

information1
information2
information3
information4
information5
information6
information7

I will write command on the terminal,

perl scripts.pl --select information3

So the result will take information3 and before that. Expected Result

information3 
information2
information1

if I write the command.

perl scripts.pl --select information6

Expected result will be:

information6
information5
information4
information3
information2
information1

My current code:

use Getopt::Long qw(GetOptions);;
use Switch;

my $read_file = 'file1.txt';
my $info_name;
my @name;
my $select;

GetOptions( "select|t=s"=> \$select, );

open(READ_FILE,"<", $read_file) || die "Cannot open file $read_file to Read! - $!";

while (<READ_FILE>) {
my $info_name = $_;
if ($info_name =~ m/$select/) {
    $info_name = $_;
    push (@name,($info_name));
    }
}
close(READ_FILE);
print "@name\n";

command:

perl scripts.pl --select information3

result:

information3

Now I only manage to get what select only. The result should show:

information3 
information2
information1

Solution

  • See if this code helps to solve your problem.

    use strict;
    use warnings;
    use Getopt::Long qw(GetOptions);
    
    my $select;
    my $flag = 0;
    my @data;
    
    GetOptions( "select|t=s"=> \$select, );
    
    open (my $fh, '<', "test.txt") or die "Cannot open a file: $!";
    
    while (my $line = <$fh>){
            chomp $line;
            push @data, $line;
            if($line =~ /^$select$/){
                    $flag = 1;
                    last;
            }
    }
    close $fh;
    if(!$flag){
            print "No match found..\n";
    } else {
            print join("\n", reverse @data)."\n";
    }