2015-09-10 3 views
1

Я знаю, как открыть файл и отобразить все содержимое с помощью PERL скрипт, но как я могу прочитать строку из файла в переменнуюPerl скрипт, чтобы открыть файл и прочитать строку

Ниже открыть файл и отобразить все содержимое

#!/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' $!"; 
} 

Мое требование

#!/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"; 

Ниже входной файл 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
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"; 
    } 
} 
1

Вам необходимо регулярное выражение. попробовать что-то вроде этого:

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) 
} 
2

Этот код предполагает несколько вещей, но если записи конфигурации последовательно то же самое, вы можете перебирать весь файл и сохранить все детали конфигурации в хэш в случае, если вам нужно больше их позднее:

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";