This is a follow-up to my earlier post.
Firstly, I hope I didn't give the impression that there was anything special about anonymous blocks and scoping. That's standard block behaviour. From "perlsub: Private Variables via my()":
The my operator declares the listed variables to be lexically confined to the enclosing block, conditional (if /unless /elsif /else ), loop (for /foreach /while /until /continue), subroutine, eval, or do/require/use'd file. ...
I used anonymous blocks to demonstrate scoping issues; however, in a real-world application, far from being anonymous, they probably would be named to allow reuse: perhaps, &read_input and &write_output, called in a loop iterating input filenames from the command line. I made some modifications to (a copy of) the earlier script, to demonstrate:
#!/usr/bin/env perl -l use strict; use warnings; use autodie; for (@ARGV) { my ($input_file, $output_file) = ($_, $_ . '__OUTPUT.txt'); my (%reformat, @order); read_input($input_file, \%reformat, \@order); write_output($output_file, \%reformat, \@order); } { my $re; INIT { $re = qr{^(H\d+,\d+,)(.*)$} } sub read_input { my ($input_file, $reformat, $order) = @_; open my $in_fh, '<', $input_file; while (<$in_fh>) { next if $. == 1; chomp; /$re/; my ($key, $str_part) = ($1, $2); push @$order, $key unless exists $reformat->{$key}; push @{ $reformat->{$key} }, $str_part; } return; } } sub write_output { my ($output_file, $reformat, $order) = @_; open my $out_fh, '>', $output_file; print $out_fh $_, join ' ', @{ $reformat->{$_} } for @$order; return; }
I've been testing like this (without any problems):
$ pm_1168253_reformat_input_WITH_FILES_PRODUCTON.pl pm_1168253_reforma +t_input_INPUT.txt pm_1168253_reformat_input_INPUT_CLONE.txt; cat pm_1 +168253_reformat_input_INPUT.txt__OUTPUT.txt; cat pm_1168253_reformat_ +input_INPUT_CLONE.txt__OUTPUT.txt H123456,20151209,THIS IS A TEST TO COMBINE ALL MY MATCHING LINES INTO +THE FIRST LINE THAT MATCHES. H654321,20151209,MATCH LINES FOR THIS ACCT INTO THE TOP LINE OF THE AC +CT H432165,20151209,SINGLE LINE FOR THIS ONE H123456,20151209,THIS IS A TEST TO COMBINE ALL MY MATCHING LINES INTO +THE FIRST LINE THAT MATCHES. H654321,20151209,MATCH LINES FOR THIS ACCT INTO THE TOP LINE OF THE AC +CT H432165,20151209,SINGLE LINE FOR THIS ONE
Notes:
"A new class of variables has been introduced. ..."
push @$order, $key unless exists $reformat->{$key};
— Ken
In reply to Re^3: Match Line And Combine Into One Line [Follow-up]
by kcott
in thread Match Line And Combine Into One Line
by jlope043
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |