在Perl中拆分的替代方法是什么?

时间:2010-05-20 07:52:20

标签: perl

我的文件包含

a: b
d: e
f: a:b:c
g: a
   b
   c
   d
   f:g:h
h: d
   d:dd:d
J: g,j

如何将此文件解析为左侧值到一个数组中,右侧到另一个数组?我尝试拆分,但我无法取回它。

我想将它们存储到哈希。

2 个答案:

答案 0 :(得分:2)

Howzabout this:

#!/usr/bin/perl
use warnings;
use strict;
my $s = 
q/a: b
d: e
f: a:b:c
g: a
   b
   c
   d
   f:g:h
h: d
   d:dd:d
   f
/;
open my $input, "<", \$s or die $!;
my @left;
my @right;
while (<$input>) {
    chomp;
    my ($left, $right) = /^(.):?\s+(.*)$/;
    push @left, $left;
    push @right, $right;
}
print "left:", join ", ", @left;
print "\n";
print "right:", join ", ", @right;
print "\n";

答案 1 :(得分:2)

为什么split不起作用?

use strict;
use warnings;

open my $file, '<', 'file.txt';
my %hash;

while (my $line = <$file>) {

    my ( $left, $right ) = split /:/, $line, 2; # Splits only on the first colon
    $right =~ s/^\s+|\s+$//g;                   # Remove leading/ trailing spaces
    $hash {$left} = $right;                     # Populate hash
}

close $file;

# print to test the output
print (join ' => ', $_, $hash{$_}),"\n" foreach keys %hash;