在这个程序中我有函数内部函数没有子函数“输出”程序循环文件并在csv文件中打印。
但是对于子函数“output”,它不是循环的,它只将第一种类型写入csv文件?
sub outputType(){
print "Choose Your Output Method"."\n";
print "1.Dumper". "\n";
print "2.TSV". "\n";
print $input;
chomp($cinput = <>);
nswitch($cinput){
case 1 : {csv();} #Function CSV will be called based on the user request
case 2 : {output();} #Function Output will be called based on user request
default : {print "Enter Correct value". "\n"; if($cinput>3 || $cinput ne "\d+"){exit;}}
}
}
outputType();
sub csv(){
my $csv = Text::CSV_XS->new ({ binary => 1 }) or
die "Cannot use CSV: ".Text::CSV_XS->error_diag ();
#$csv->eol ("\r\n");
open my $f1, "<:encoding(utf8)", "upcs.tsv" or die "upcs.tsv: $!";
#open my $f1, '<', 'upcs.tsv';
my $sem3 = Net::Semantics3::Products->new (
api_key => 'SEM3F9C9',
api_secret => 'OGU4N2M3OTI4NGY',
);
#my $csv = Text::CSV->new ({
#'quote_char' => '',
#'escape_char' => '',
# 'sep_char' => "\t",
# 'binary' => 1
#});
my @field;
while(my $rows = $csv->getline ($f1)){
#print STDERR Dumper $rows->[0];
my $a = $rows->[0]."\n";
push(@field,$a);
#$csv -> print($f3,$_) for \@field
}
#close $f1;
#$csv->eol ("\r\n");
#print scalar(@field);
open my $f3, ">:encoding(utf8)", "frameworkresult.csv" or die "frameworkresult.csv: $!";
$csv->eol ("\r\n");
#open my $f3, '>', 'frameworkresult.tsv';
my @headers = qw/
Name
UPC
Price/;
$csv->print ($f3, $_) for \@headers;
$csv->eol ("\r\n");
my $ctr= 0;
foreach my $input (@field){
print $input;
$sem3->add("products","upc",$input);
my $nextProductsRef = $sem3->get_products();
my $results = $nextProductsRef->{results};
my @data;
foreach my $result (@$results) {
$ctr++;
#print STDERR " Name: ".$result->{name}."\n";
#print STDERR " UPC: ".$result->{upc}."\n";
#print STDERR " Price: ".$result->{price}."\n";
my $f = $result->{name};
my $g = $result->{upc};
my $h = $result->{price};
push(@data,$f);
push(@data,$g);
push(@data,$h);
#exit if $ctr >2;
}
print Dumper(@data);
sub output(){
$csv->print($f3,\@data);
}
$csv->eol ("\r\n");
}
}
答案 0 :(得分:0)
您似乎正在编译@data
,但实际上并没有输出它。也许这只是开发过程中的一个错误?
将呼叫转移到$csv->print
到您的循环:
push(@data,$f);
push(@data,$g);
push(@data,$h);
$csv->print($f3,\@data);
#exit if $ctr >2;
}
<强>更新强>
因为你问过如何使用子程序来做这件事:
push(@data,$f);
push(@data,$g);
push(@data,$h);
amazing_subroutine($csv, $f3, \@data);
#exit if $ctr >2;
}
sub amazing_subroutine {
my ($csv, $f3, $dataref) = @_;
$csv->print($f3, $dataref);
}