perl - 如何在Perl中使用变量进行替换?

标签 perl variables substitution

我有几个文本文件,它们曾经是数据库中的表,现在已被分解。我正在尝试重新组装它们,一旦将它们变成可用的形式,这将很容易。第一个文件“keys.text”只是标签列表,格式不一致。喜欢:

Sa 1 #
Sa 2
U 328 #*

它始终是字母,[空格],数字,[空格],有时还包括符号。与这些键匹配的文本文件是相同的,然后是一行文本,也由空格分隔或定界。
Sa 1 # Random line of text follows.
Sa 2 This text is just as random.
U 328 #* Continuing text...

我想在下面的代码中执行的操作是将“keys.text”中的键与.txt文件中的相同键进行匹配,然后在键和文本之间放置一个制表符。我确定我忽略了一些非常基本的内容,但是得到的结果看起来与源.txt文件相同。

在此先感谢您提供任何线索或帮助!
#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;
open(IN1, "keys.text");

my $key;

# Read each line one at a time
while ($key = <IN1>) {

# For each txt file in the current directory
foreach my $file (<*.txt>) {
  open(IN, $file) or die("Cannot open TXT file for reading: $!");
  open(OUT, ">temp.txt") or die("Cannot open output file: $!");

  # Add temp modified file into directory 
  my $newFilename = "modified\/keyed_" . $file;
  my $line;

  # Read each line one at a time
  while ($line = <IN>) {

     $line =~ s/"\$key"/"\$key" . "\/t"/;
     print(OUT "$line");

  }
  rename("temp.txt", "$newFilename");
 }   
}

编辑:只是为了澄清,结果也应该保留键中的符号,如果有的话。因此,它们看起来像:
Sa 1 #      Random line of text follows.
Sa 2        This text is just as random.
U 328 #*    Continuing text...

最佳答案

正则表达式对我来说似乎很奇怪。不会

$line =~ s/$key/$key\t/;

工作更好?

另外,IIRC,<IN1>将换行符保留在$ key的末尾。 chomp $key摆脱了这一点。

而且,在写入文件句柄时,请不要在print args周围加上括号,尤其是在括号中。无论它是否存在,它看起来都是错误的,并分散了人们对实际问题的注意力。

关于perl - 如何在Perl中使用变量进行替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3295401/

相关文章:

linux - 从 CPAN 安装 perl 模块时获取 "Proxy authentication Required"消息

c# - 将 C# 变量设置为从数据库中选择

Python:在字典中将变量链接/绑定(bind)在一起

javascript - 如何在同一页面上拥有相同的 javascript 变量?

bash - 当我使用 'sh' 运行 Bash 代码时,为什么它会失败?

perl - 如果其父进程先完成,后台进程是否完成?

mysql - Perl TLS1.2 到 MySql Db

python - Perl 在获取 HTML 页面方面胜过 Python?

regex - 为什么 perl regex .* 无法识别空分隔记录中的\n。 $/="\0'

regex - 如何在 perl 替换运算符的替换端使用表达式?