http://www.perlmonks.org?node_id=1028463


in reply to Cool way to parse Space Separated Value and CSV files

Since you state that the first line in the file is important it might be as well to treat it differently by assigning it to a separate scalar variable. Also, when you split the header to get the column names you could save having to do the shift by assigning the first value to undef which can act as a sort of programmatic bit bucket.

use strict; use warnings; use 5.014; use Data::Dumper; open my $inFH, q{<}, \ <<EOD or die qq{open: < HEREDOC: $!\n}; # lastname firstname age gender phone mcgee bobby 27 M 555-555-5555 kincaid marl 67 M 555-666-6666 # comment hofhazards duke 22 M 555-696-6969 EOD my( $header, @lines ) = <$inFH>; close $inFH or die qq{close: < HEREDOC: $!\n}; my( undef, @keys ) = split m{\s+}, $header; foreach my $line ( @lines ) { next if $line =~ m{(?x) ^ \s* (?: (?-x:#) | $ )}; my %hash; @hash{ @keys } = split m{\s+}, $line; print Data::Dumper->Dumpxs( [ \ %hash ], [ qw{ *hash } ] ); }

The output.

%hash = ( 'firstname' => 'bobby', 'lastname' => 'mcgee', 'phone' => '555-555-5555', 'age' => '27', 'gender' => 'M' ); %hash = ( 'firstname' => 'marl', 'lastname' => 'kincaid', 'phone' => '555-666-6666', 'age' => '67', 'gender' => 'M' ); %hash = ( 'firstname' => 'duke', 'lastname' => 'hofhazards', 'phone' => '555-696-6969', 'age' => '22', 'gender' => 'M' );

The technique falls to pieces somewhat when your space-separated files contain fields or headers containing spaces, or a CSV file with commas dotted around. You would then reach for something like Text::CSV.

I hope this is of interest.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Cool way to parse Space Separated Value and CSV files
by Anonymous Monk on May 21, 2018 at 07:23 UTC
    How to take input from user rather than hard coding for this solution

      I assume that you want to run the program on a user-specified file instead of the hardcoded file?

      Command line parameters are available in the @ARGV array, see perlvar.

      You can read user input from STDIN, like my $filename = <STDIN>;

      Once you have the filename, modify the open statement to use a filename instead of opening a here-document.

      A reply falls below the community's threshold of quality. You may see it by logging in.