我是一名初学程序员,已经获得了为期一周的任务来构建一个复杂的程序,但是很难开始。我已经获得了一组数据,并且根据字母是M还是F,第二列将目标分成两个单独的数组。 这是我到目前为止的代码:
#!/usr/local/bin/perl
open (FILE, "ssbn1898.txt");
$x=<FILE>;
split/[,]/$x;
@array1=$y;
if @array1[2]="M";
print @array2;
else;
print @array3;
close (FILE);
我该如何解决这个问题?请尝试使用我上周编写的最简单的术语! 谢谢
答案 0 :(得分:3)
首先关闭 - 你用逗号分隔,所以我假设你的数据看起来像这样:
one,M
two,F
three,M
four,M
five,F
six,M
您的代码存在一些问题:
启用strict
和warnings
。警告您关于代码可能出现的问题
打开最好写成open ( my $input, "<", $filename ) or die $!;
<FILE>
中的一行 - 因为如果您将其分配给标量$x
,它只会读取一行。 所以要做你基本上想做的事情:
#!/usr/local/bin/perl
use strict;
use warnings;
#define your arrays.
my @M_array;
my @F_array;
#open your file.
open (my $input, "<", 'ssbn1898.txt') or die $!;
#read file one at a time - this sets the implicit variable $_ each loop,
#which is what we use for the split.
while ( <$input> ) {
#remove linefeeds
chomp;
#capture values from either side of the comma.
my ( $name, $id ) = split ( /,/ );
#test if id is M. We _assume_ that if it's not, it must be F.
if ( $id eq "M" ) {
#insert it into our list.
push ( @M_array, $name );
}
else {
push ( @F_array, $name );
}
}
close ( $input );
#print the results
print "M: @M_array\n";
print "F: @F_array\n";
你可以更简洁地做到这一点 - 我建议可能接下来看看哈希值,因为那时你可以关联键值对。
答案 1 :(得分:2)
List::MoreUtils中有一个part
功能可以完全满足您的需求。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use List::MoreUtils 'part';
my ($f, $m) = part { (split /,/)[1] eq 'M' } <DATA>;
say "M: @$m";
say "F: @$f";
__END__
one,M,foo
two,F,bar
three,M,baz
four,M,foo
five,F,bar
six,M,baz
输出结果为:
M: one,M,foo
three,M,baz
four,M,foo
six,M,baz
F: two,F,bar
five,F,bar
答案 2 :(得分:0)
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my @boys=();
my @girls=();
my $fname="ssbn1898.txt"; # I keep stuff like this in a scalar
open (FIN,"< $fname")
or die "$fname:$!";
while ( my $line=<FIN> ) {
chomp $line;
my @f=split(",",$line);
push @boys,$f[0] if $f[1]=~ m/[mM]/;
push @girls,$f[1] if $f[1]=~ m/[gG]/;
}
print Dumper(\@boys);
print Dumper(\@girls);
exit 0;
# Caveats:
# Code is not tested but should work and definitely shows the concepts
#
答案 3 :(得分:0)
事实上同样的事情......
#!/usr/bin/perl
use strict;
my (@m,@f);
while(<>){
push (@m,$1) if(/(.*),M/);
push (@f,$1) if(/(.*),F/);
}
print "M=@m\nF=@f\n";
或者&#34; perl -n&#34; (=对于所有行)变体:
#!/usr/bin/perl -n
push (@m,$1) if(/(.*),M/);
push (@f,$1) if(/(.*),F/);
END { print "M=@m\nF=@f\n";}