IyengarRaj has asked for the wisdom of the Perl Monks concerning the following question:

Guys, I need help with this. I need to write a perl program that should output a file. Parameters are: SomePerl.pl infile outfile 8 5 10. infile can be any standard file with a header record with a delimiter. Columns (numbers, names and position) can change from file to file. outfile is the output I want with the following: asset_id~asset_tag~asset_cl~col1|col2|col3|.... where asset_id, asset_tag and asset_cl is mapped to columns 8, 5 and 10. Column header in the file may not be exactly named as asset_id, asset_tag or asset_cl. Output file row should look like: col8~col5~col10~col1|col2|col3|col4|col5|col6|col7|col8|col9|col10 I am new to perl and how would I achieve this? Appreciate your help. Thanks.

Replies are listed 'Best First'.
Re: Parsing a generic file
by Anonymous Monk on Jul 25, 2013 at 00:14 UTC

    I am new to perl and how would I achieve this?

    You would super search and "google site:perlmonks.org" to find a dozen or so programs that do this already

    They all use Text::CSV or Text::CSV_XS, some use App::CCSV , all you gotta do is find them

Re: Parsing a generic file
by mtmcc (Hermit) on Jul 25, 2013 at 03:46 UTC
    The monk is right. And it won't help you much if someone just writes the code for you. Have a look at How do I post a question effectively? If you actually write some code, and ask about where you're stuck, people will be more likely to help you out!

    Best of luck.

Re: Parsing a generic file
by hdb (Monsignor) on Jul 25, 2013 at 13:47 UTC

    Nice exercise for Text::CSV fans:

    use strict; use warnings; use Text::CSV; my( $infile, $outfile, @cols ) = @ARGV; print "Reading from $infile.\n"; print "Writing to $outfile.\n"; print "Target columns are @cols.\n"; open my $in, "<", $infile or die "Cannot open $infile: $!\n"; open my $out, ">", $outfile or die "Cannot open $outfile: $!\n"; $_-- for @cols; # correct column numbering my $csv = Text::CSV->new( ); my $pipe = Text::CSV->new( { sep_char => '|' } ); my $tilde = Text::CSV->new( { sep_char => '~', eol => "\n" } ); while( my $line = $csv->getline( $in ) ) { $pipe ->combine( @$line ); $tilde->combine( @$line[@cols], $pipe->string ); print $out $tilde->string; } close $out; close $in;
      Thanks you very much guys. Really appreciate it very much. Clue about Text::CSV was the key element and how easily this can be done using that. I love this group. Thanks again.