in reply to What can I do to improve my code - I'm a beginner
I found your code hard to follow. I present an alternative below and will offer a few comments.
#!/usr/bin/perl use strict; use warnings; use Getopt::Long; use Date::Calc qw/Date_to_Time/; my @files = ('FiveSecondSamples.txt'); my @weekDay_text = qw(Sun Mon Tue Wed Thu Fri Sat); #### This is the Main Loop..., note that the main loop is "short" foreach my $in_file (@files) { open my $fh_in, '<', "$in_file" or die "unable to open $in_file $ +!"; open my $fh_out, '>', "$in_file"."_outfile.txt" or die "unable to open outfile for $in_file $!"; # deal with the special first line # my $current_time = process_header_line( $fh_in, $fh_out); # process the data in one minute chunks (12 samples per minute) # while ($current_time = process_one_minute($fh_in, $fh_out, $curren +t_time)){}; } #### #### The Main Loop is "over", now subroutines in the code... #### ## Process the input header line for start time and setup the output h +eader # sub process_header_line { my($fh_in, $fh_out) = @_; my $first_line = <$fh_in>; print $fh_out "#$first_line"; ### debug ## first input line as com +ment my ($year1,$month1,$day1,$hour1,$min1,$sec1, $year2,$month2,$day2,$hour2,$min2,$sec2,) = $first_line =~ /(\ +d+)/g; # with caveats my $start_time = Date_to_Time($year1,$month1,$day1,$hour1,$min1,$s +ec1); print $fh_out "Date\t\tTime\t\tDay\tmg\n"; # print output file +title line return $start_time; } ## Process each minute of data (12 samples) ## A block of data with less than 12 samples is not processed # sub process_one_minute { my ($fh_in, $fh_out, $current_time) = @_; my $total = 0; for (1..12) { my $in = <$fh_in>; return 0 unless defined $in; # No output if <12 samples in this + set. # This the "eof, "file empty" retu +rn, # no more complete sets of 12 samp +les my ($num) = split(',',$in); $total += $num; } my $avg = $total/12; $current_time += 60; # add 60 seconds to the "epoch time" my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($current_time); printf $fh_out "%d-%02d-%02d\t%02d:%02d:%02d", $year+1900, $mon+1, $mday, $hour, $min, $sec; print $fh_out "\t",$weekDay_text[$wday]; print $fh_out "\t$avg\n"; return $current_time; }
acceleration (mg) - 2013-10-09 10:00:00 - 2013-10-16 09:59:55 - sample +Rate = 5 seconds, imputed 46.3, 0 17.1, 0 30.1, 0 38.4, 0 97.1, 0 87.3, 0 84, 0 78.5, 0 67.9, 0 83.5, 0 155, 0 103.5, 0
#acceleration (mg) - 2013-10-09 10:00:00 - 2013-10-16 09:59:55 - sampl +eRate = 5 seconds, imputed Date Time Day mg 2013-10-09 10:01:00 Wed 74.0583333333333
|
|---|