Perl建议 - 接收文件并更改内容

时间:2011-08-17 23:10:25

标签: perl

我有一些关于如何处理我想用Perl编写的脚本的建议请求。基本上我有一个看起来像的文件:

  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4

在某些关键字如宠物和颜色之后会有数字。我希望能够接收文件并查找这些关键字(其中有5个或6个),然后将数字更改为该数字对应的单词。也就是说关键字“Pet”---> 0 =狗,1 =猫,2 =鱼。对于关键字“颜色”0 =红色,1 =蓝色,2 =紫色,3 =棕色,4 =白色。脚本应该找到并更改这些数字。目标应该是一个输出文件,如下所示:

      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white

我一直在努力解决这个问题。我在线查询也许我可以做一些哈希或其他东西,但我对Perl相对较新,并且不知道如何解决这个问题....任何建议都会非常感激!

由于

5 个答案:

答案 0 :(得分:2)

如果我们讨论的是一小组值,您可以使用数组哈希:

%lookups = ( pet => [ "dog", "cat", "fish" ],
             color => [ "red", "blue", "purple", "brown", "white" ] );

然后,当您阅读文件时,请根据哈希检查每个关键字。如果它有一个包含该关键字的键,请将您读取的行中的值替换为哈希值。

答案 1 :(得分:0)

这应该这样做

use strict;

my $inputFileName = 'E:\test.txt';
my $outputFileName = 'E:\test2.txt';


my %Colors = ( 1 => 'Red' , 2 => 'Green' , 4 => 'Blue' );
my %Pets = ( 1 => 'Dog' , 2 => 'Cat' );

open( IN , "<" , $inputFileName) or die "$inputFileName could not be opened $!";
open( OUT, ">" , $outputFileName) or die "$outputFileName could not be opened $!";

while(<IN>)
{
    my $line = $_;
    if (/^(\s*pet\s*:\s*)(\d+)/ )
    {
        $line = $1. $Pets{$2} . "\n";
    }
    elsif (/\s*^color\s*:\s*(\d+)/ )
    {
       $line = $1. $Colors{$2} . "\n";
    }

    print OUT $line;
}
close(IN);
close(OUT);

答案 2 :(得分:0)

如果案例不多,您可以尝试这样的事情,与perl -p一起运行:

if (/^id/) 
{
    s/\d+/%h=(1=>"dog",2=>"warf",3=>"ee");$h{$&}/e;
}
if (/^other/) 
{ 
    s/\d+/%h=(1=>"other_thing",3=>"etc",4=>"etc2");$h{$&}/e;
}

修改

要自动化测试,你可以做类似的事情(也从zigdon中获取哈希的想法):

my @interesting_tags = ("color", "pet");
my $regexp = "(" .  join("|" , @interesting_tags) . ")";

my %lookups = ( pet => [ "dog", "cat", "fish" ],
                color => [ "red", "blue", "purple", "brown", "white" ] );


while (<>)
{
    if (/$regexp/)
    {
        my $element = $&;
        s/\d+/$lookups{$element}[$&]/e;
    }
}

答案 3 :(得分:0)

使用zigdon的建议

#!/usr/bin/perl
use strict;
use warnings;
use 5.014;

my %param = (pet   => [qw/dog cat fish/],
             color => [qw/ red blue purple brown white/],
);

while (<DATA>) {
    if (/^(pet|color):\s*(\d)$/) {
        print "$1: $param{ $1 }[$2]\n";
    }
    else {
        print;  
    }
}


__DATA__
id: 1
Relationship: ""
name: shelby
pet: 1
color:4

答案 4 :(得分:0)

用法: script.pl file.txt > output.txt

use strict;
use warnings;

my %tags = (
    "pet" => [ qw(dog cat fish) ],
    "color" => [ qw(red blue purple brown white) ],
);

my $rx = join '|', keys %tags;

while (<>) {
    s/^\s*($rx):\s*(\d+)/$1: $tags{$1}[$2]/;
    print;
}