2012-05-30 43 views
0

卸下空間我有以下文件:的Perl:在線路

firstname=John 
name=Smith 
address=Som 
ewhere 

正如你可以看到,該地址是在2線(與所述第二線通過的空間開始)。

我必須將「好」輸出(「地址=某處」)寫入另一個文件。

這是第一個腳本(有點複雜),我寫道:

foreach $line (@fileIN) { 
    if ($lastline eq "") { 
     $lastline = $line; 
    } else { 
     if ($line =~/^\s/) { 
      print $line; 
      $line =~s/^\s//; 
      $lastline =~s/\n//; 
      $lastline = $lastline.$line; 
     } else { 
      print fileOUT $lastline; 
      $lastline = $line; 
     } 
    } 
} 

$線=〜/^\ S/=>此正則表達式在$線路匹配的空間,而不是隻在開始。

我也試着寫了一個簡單的,但它並沒有太多的工作:

perl -pe 's/$\n^\s//' myfile 

回答

1

你似乎做了太多的工作。我會這樣做:

my $full_line; 
foreach my $line (@fileIN) { 
    if ($line =~ /^\s+(.+)\Z/s){     # if it is continuation 
      my $continue = $1;      # capture and 
      $full_line =~ s/[\r\n]*\Z/$continue/s; # insert it instead last linebreak 
    } else {          # if not 
      if(defined $full_line){ print $full_line } # print last assembled line if any 
      $full_line = $line;     # and start assembling new 
    } 
} 
if(defined $full_line){ print $full_line }   # when done, print last assembled line if any 
+0

工作正常:) 謝謝! – user1425653

+1

你可能會像choroba一樣使用'chomp',這會更像「perl-like」的方式來做到這一點。 – kevlar1818

0

檢查我的解決方案只有1個正則表達式:)

my $heredoc = <<END; 
firstname=John 
name=Smith 
address=Som 
ewhere 
END 

$heredoc =~ s/(?:\n\s(\w+))/$1/sg; 
print "$heredoc";` 
+0

它只會用於啜飲整個文件。 –

+0

是否可以在變量中獲取整個文件並對其進行替換? Like: 'open(FILE,「$ myfile」)||死「打開:$!」; $ FILE =〜s /(?:\ n \ s(\ w +))/ $ 1/sg; print $ FILE;' – user1425653

+1

@ user1425653:'my $ file = do {local $ /; <$filehandle>};' – flesk

1

例如這樣嗎?

while (<DATA>) { 
    chomp; 
    print "\n" if /=/ and $. - 1; # do not insert empty line before the 1st line 
    s/^\s+//;      # remove leading whitespace 
    print; 
} 
print "\n";      # newline after the last line 

__DATA__ 
firstname=John 
name=Smith 
address=Som 
ewhere 
+1

如果文件將採用其他格式?沒有具體提到每行應該有single =,只有那些ideally行應該連接到previous。 –

+0

@ OlegV.Volkov:好吧,沒有完整的規範,只能猜測。 – choroba

+0

一行可以包含多個=正如你所說:) – user1425653