这些正则表达式之间有什么区别 - perl

时间:2013-04-03 15:49:29

标签: perl

我在文件image1.hd

中有一行文字
axial rotation:=0.880157

我想要这个号码。使用核心perl我这样做

open FILE, "<", "$Z_DIR/image1.hd" or die $!;
  while (<FILE>){
    if (/axial rotation:=(\S+)/)
      {
    $axial_rot = $1;
      }
  }
  close FILE;

返回所需的输出= 0.880157

我更喜欢一个班轮,因为我会做类似于其他一些文件。之前我了解了File :: Slurp模块,我尝试了以下内容,并在assertion背后进行了正面观察

my $axial_rot = read_file("$Z_DIR/image1.hd") =~ /(?<=axial rotation:=)\S+/

返回1 - 无论正则表达式如何。如何更改后一个正则表达式以实现所需的输出

2 个答案:

答案 0 :(得分:5)

问题是你在标量上下文中使用赋值,这使匹配返回匹配数。通过切换到列表上下文,您可以使用匹配组返回所需的子字符串:

my ($axial_rot) = read_file("$Z_DIR/image1.hd") =~ /axial rotation:=(\S+)/;

答案 1 :(得分:0)

除非你需要,否则你真的不应该将整个文件读入内存。

use strict;
use warnings;
use autodie;

sub find_in_file{
  my($filename,$regex) = @_;
  my @return;

  open my $fh, '<', $filename; # or die handled by autodie

  while( my $line = <$fh> ){
    last if (@return) = $line =~ $regex
  }

  close $fh; # or die handled by autodie

  return $return[0] unless wantarray;
  return @return;
}

my $Z_DIR = '.';
my $axial_rot = find_in_file( "$Z_DIR/image1.hd", qr'\baxial rotation:=(\S+)' );
相关问题