in reply to Handling different data types of the same data
so how can I avoid having three separate csv parsing subs?
One way would be to build an iterator for each different input type and pass that to the parsing routine. Something like this:
use strict; use warnings; use Carp; use Scalar::Util qw( openhandle ); sub filehandle_iterator { my $fh = shift; return unless openhandle( $fh ); return sub { my $row = <$fh>; chomp $row if defined($row); return $row; }; }; sub file_iterator { my $filename = shift; no warnings; # to avoid warnings about filenames with \n in return unless open my $fh, '<', $filename; return filehandle_iterator( $fh ); }; sub string_iterator { my $csv_string = shift; my @lines = split( /\n/, $csv_string ); return sub { shift @lines }; }; sub parse_csv { my $csv_input = shift; my $row_iterator = file_iterator( $csv_input ) || filehandle_iterator( $csv_input ) || string_iterator( $csv_input ) || croak 'could not find iterator'; while ( my $row = $row_iterator->() ) { # ... do stuff with row ... print "> $row <\n"; }; };
|
|---|