打开文件并读取字符串的Perl脚本

打开文件并读取字符串的Perl脚本,perl,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";

我知道如何使用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' $!";
}
使用严格;
使用警告;
打开(我的$fh,“
使用严格;
使用警告;

打开(my$fh,“您需要一个regexp。请尝试以下操作:

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

您需要一个regexp。请尝试以下操作:

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

这段代码假设了一些情况,但如果配置条目始终相同,则可以迭代整个文件并将所有配置详细信息存储在散列中,以防以后需要更多配置详细信息:

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";
使用警告;
严格使用;

打开我的$fh,“这段代码假设了一些事情,但是如果配置条目始终相同,您可以迭代整个文件并将所有配置细节存储在一个散列中,以防以后需要更多配置细节:

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";
使用警告;
严格使用;
打开我的$fh,'
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";