网络浪子 发表于 2017-5-19 06:56:18

perl的嵌套循环是如何写

perl的嵌套循环是如何写

如下代码,只能进行到第一层小循环,问题出在哪里?

#!perl
use strict;
use warnings;
my $work_dir = "/home/dell/telexpr_xx/scp/";
my $in_file = $work_dir . "3011_test_0101_37269.scp";
my $final_file = $work_dir . "result_3011_final.mlf";
my $out_file = $work_dir."result_3011_out.mlf";
open (INFILE, "$in_file");
open(FINALFILE, "$final_file")|| die "Cannot open the newfile: $!\n";
open (OUTFILE,">>$out_file")|| die "Cannot open the newfile:$!\n";
foreach my $text (<INFILE>) {
$text =~ /3011_20101110_1616_A_+\.mfc/;
my $var = "$&";
$var =~ s/mfc/rec/;
# print "$var\n";
my $final_text = &Find_Sex($var,$text);
printOUTFILE $final_text;
}
close(INFILE);
close(OUTFILE);
close(FINALFILE);

#==============sub function===============
sub Find_Sex{
my( $sub_var,$sub_text) = @_;
#print "The sub_var is: $sub_var\n";
#print "The sub_text is: $sub_text\n";
while( my $line = <FINALFILE> ){
if ($line =~ /($sub_var)/ && $line =~ /F/) {
$sub_text =~ s/\.mfc/\.mfc_F/;
}
elsif ($line =~ /($sub_var)/ && $line =~ /M/) {
$sub_text =~ s/\.mfc/\.mfc_M/;
}
}
return $sub_text;
}


你首先要确定问题出在哪里
首先思考下读文件怎么个读法?<>在什么情况下返回假?一次文件读完了它下次会帮你重新读?
看下面的修改:

#!perl
use strict;
use warnings;
my $work_dir = "/home/dell/telexpr_xx/scp/";
my $in_file = $work_dir . "3011_test_0101_37269.scp";
my $final_file = $work_dir . "result_3011_final.mlf";
my $out_file = $work_dir."result_3011_out.mlf";
open (INFILE, "$in_file");
#open(FINALFILE, "$final_file")|| die "Cannot open the newfile: $!\n";
open (OUTFILE,">>$out_file")|| die "Cannot open the newfile:$!\n";
foreach my $text (<INFILE>) {
$text =~ /3011_20101110_1616_A_+\.mfc/;
my $var = "$&";
$var =~ s/mfc/rec/;
# print "$var\n";
my $final_text = &Find_Sex($var,$text);
printOUTFILE $final_text;
}
close(INFILE);
close(OUTFILE);

#==============sub function===============
sub Find_Sex{
open(FINALFILE, "$final_file")|| die "Cannot open the newfile: $!\n";
my( $sub_var,$sub_text) = @_;
#print "The sub_var is: $sub_var\n";
#print "The sub_text is: $sub_text\n";
while( my $line = <FINALFILE> ){
if ($line =~ /($sub_var)/ && $line =~ /F/) {
$sub_text =~ s/\.mfc/\.mfc_F/;
}
elsif ($line =~ /($sub_var)/ && $line =~ /M/) {
$sub_text =~ s/\.mfc/\.mfc_M/;
}
}
close(FINALFILE);
return $sub_text;
}


这次就可以,文件读取出了问题。
还有一种写法:

use strict;
use warnings;
my $u = "tu.txt";
my $p = "tp.txt";
my $user;
my $pass;
open( Ur, "< $u" ) || die "can't open $u!";
open( Ps, "< $p" ) || die "can't open $p!";
while ( $user = <Ur> ) {
chomp($user);
seek Ps, 0, 0;
while ( $pass = <Ps> ) {
chomp($pass);
print $user, ":", $pass, "\n";
}
}
close(Ur);
close(Ps);
页: [1]
查看完整版本: perl的嵌套循环是如何写