【问题标题】:Perl script to open a file and read a stringPerl 脚本打开文件并读取字符串
【发布时间】:2015-09-10 11:58:19
【问题描述】:

我知道如何使用 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 
#############################################################################################

【问题讨论】:

    标签: perl


    【解决方案1】:
    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";
        }
    }
    

    【讨论】:

      【解决方案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";
      

      【讨论】:

        【解决方案3】:

        你需要一个正则表达式。尝试这样的事情:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多