如何使用Perl将一个文件的列替换为另一个文件的列?

Mik*_*ke 0 perl

假设文件1有两列,看起来像:

fuzz          n.  flowering shrub of the rhododendron family
dyspeptic     adj. bright blue, as of the sky 
dysplexi      adj. of Byzantium or the E Roman Empire
eyrie         adj. of the Czech Republic or Bohemia
azalea        adj. suffering from dyslexia
Czech         adj. suffering from dyspepsia
Byzantine     n. eagle's nest
azure         n. mass of soft light particle

文件2只有一个clumn,看起来像:

azalea
azure
Byzantine
Czech
dyslexic
dyspeptic
eyrie
fuzz

我希望文件1的第一列替换为文件2的列.因此,文件3应如下所示:

azalea        n.  flowering shrub of the rhododendron family
azure         adj. bright blue, as of the sky 
Byzantine     adj. of Byzantium or the E Roman Empire
Czech         adj. of the Czech Republic or Bohemia
dyslexic      adj. suffering from dyslexia
dyspeptic     adj. suffering from dyspepsia
eyrie         n. eagle's nest
fuzz          n. mass of soft light particle

我有一种感觉,就是有一种或另一种简单的方法可以做这种工作而且它很可能是一些方便的模块,但是现在我甚至不能以最低效的方式做到这一点.我尝试了一堆代码

while<$line1 = file1>{
while<$line2 = file2>{
join $line,$line2 
Run Code Online (Sandbox Code Playgroud)

但没有运气.有人能指出我正确的方向吗?一如既往地感谢任何指导.

Chr*_*utz 6

如果你想同时读两行,试试这个:

while(defined(my $line1 = <file1>)
      and defined(my $line2 = <file2>)) {
  # replace contents in $line1 with $line2 and do something with $line1
}
Run Code Online (Sandbox Code Playgroud)

一旦一行耗尽,这将停止工作,因此在此循环结束时查看两个文件是否为空可能是个好主意:

die "Files are different sizes!\n" unless eof(file1) == eof(file2);
Run Code Online (Sandbox Code Playgroud)

当然,在现代Perl中,您可以将文件句柄存储在词法范围的变量中,如下所示:

open my $fh, ...
Run Code Online (Sandbox Code Playgroud)

然后<FILEHANDLES>用漂亮的lexically scoped 替换丑陋的全局<$filehandles>.它更好,而且它更好

  • @jrockway - 如果你只用`while($ line = <file>)循环遍历一个文件`Perl添加`defined()`检查,那么OP可能不知道它并且可能天真地写`while($ line1 = <file1>和$ line2 = <file2>)`当其中一个读取空白行(或行"0")时将失败. (3认同)
  • 它有点毛茸茸,而且很少见.如果你的文件非常小,你可以很容易地将它们都插入到数组中并在内存中使用它们.但是,如果预计此代码在较旧的计算机或大型文件上运行,则该方法将占用大量内存,并且不鼓励使用. (2认同)