RahulR RahulR - 5 months ago 7x
Perl Question

search a string in a file and operate on the line in perl

qa1 /apps/dir1 qavm01,qavm02,qavm03
qa2 /apps/dir2 qavm01,qavm02,qavm03
qa3 /apps/dir3 qavm01,qavm02,qavm03
cpz /apps/cpz1 ctg201,ctg202

I have a file as above.

  1. I want to find the line that matches
    . This will change each time, depending on what the user enters. I have an HTML front end for providing the value. I want the CSV pattern in an array so I can use it for the next operation.

  2. Using a loop I need to connect to each server (the CSV pattern in the file is a list of servers) and access the directory.

I am new to Perl. I can do the second one. But I'm not sure how I can do the first part.


This should work for you as a basic framework

Note that it's up to you to write the part that gets the environment name into the $input variable, and the connection to the server

use strict;
use warnings qw/ all FATAL /;

use constant ENV_FILE => 'env_data.txt';

my $input = 'qa1';

open my $fh, '<', ENV_FILE
    or die sprintf qq{Unable to open "%s" for input: $!}, ENV_FILE;

while ( <$fh> ) {
    next unless /\S/;
    my ($env, $dir, $servers) = split;
    next unless $env eq $input;

    for my $server ( split /,/, $servers ) {

        ## Connect to $server and access $dir

        last LINE;