Perl中拆分的替代方法是什么?
我的文件包含Perl中拆分的替代方法是什么?,perl,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 如何将该文件解析为一个数组的左侧值和另一个数组的右侧值?我试过用split,但没能把它拿回来 我想将它们存储到哈希中。如何处理: #!/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
a: b
d: e
f: a:b:c
g: a
b
c
d
f:g:h
h: d
d:dd:d
J: g,j
如何将该文件解析为一个数组的左侧值和另一个数组的右侧值?我试过用split,但没能把它拿回来
我想将它们存储到哈希中。如何处理:
#!/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";
#/usr/bin/perl
使用警告;
严格使用;
我的$s=
q/a:b
d:e
f:a:b:c
g:a
B
C
D
f:g:h
h:d
d:dd:d
F
/;
打开我的$input,“为什么不工作
使用严格;
使用警告;
打开我的$file,,$,$,$,$哈希{$}),“\n”foreach键%hash;
您能否更具体地说明在两个结果数组中需要什么?例如@left=('a','d','f','g','h'));@right=???我想把它们存储到hash中。你把这个作为社区维基是为了什么?为了避免自己在一个你花了很少精力的问题上失去代表?这个问题的标题甚至有一个拼写错误!也许那里有足够的信息让你自己解决其余的问题?我用这个信息解决了这个问题,这很奇怪被接受的答案。从这个问题上,我猜测分割不起作用,因为不是每一行都有一个前导字段。是的,但很难确定OP需要什么。这是一个定义不清的问题
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;