1

I know how to open a file and display entire content using perl script, but how can i read a string from file into a variable

Following is to open file and display entire content

#!/usr/bin/perl 
use strict;
use warnings;

my $filename = '/home/abc/data.txt';
if (open(my $fh, '<', $filename)) {
  while (my $row = <$fh>) {
    chomp $row;
    print "$row\n";
  }
} else {
  warn "Could not open file '$filename' $!";
}

My requirement is

   #!/usr/bin/perl 
    use strict;
    use warnings;

    my $filename = '/home/abc/data.txt';
    my $foo = ""
    if (open(my $fh, '<', $filename)) {
     ---- Read test_reg_ip string from data.txt into variable 
         $foo=test_reg_ip;
    } else {
      warn "Could not open file '$filename' $!";
    }
    print "$foo\n";

Following is the input file data.txt

#############################################################################################
# mon_server_ip
# This parameter value should point to the IP address where the mon Server
# is installed
#############################################################################################
mon_server_ip = 127.0.0.1

#############################################################################################
# test_reg_ip
# This parameter value should point to the IP address where reg server is
# installed
#############################################################################################
test_reg_ip = 127.0.0.1

#############################################################################################
# mon_port
# This parameter value should point to the mon port 
#############################################################################################

3 Answers 3

3
use strict;
use warnings;
open (my $fh, "<", "file.txt") or die $!;
while(<$fh>){
    if ($_ = /test_reg_ip = (.*)/){
        my $ip = $1;
        print "IP is $ip\n";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

This code assumes a few things, but if the config entries are consistently the same, you could iterate the entire file and store all the config details in a hash in case you need more of them later:

use warnings;
use strict;

open my $fh, '<', 'in.txt'
  or die $!;

my %data;

while (<$fh>){
    if (/^(\w+)\s*=\s*(.*)$/){
        $data{$1} = $2;
    }
}

print "$data{test_reg_ip}\n";

print "$data{mon_server_ip}\n";

Comments

1

you need a regexp. try something like this:

if ($row =~ /test_reg_ip\s=\s(\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3})/) {
   my  $foo = $1; # your IP goes here, on the first (and only matched group)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.