in reply to Re^3: Processing CSV File
in thread Processing CSV File
Hi, Perl3r.
Try the following:
#!/usr/bin/perl # use strict; use warnings; $ARGV[0] or die "Usage: $0 <filename> [<filename>] ..."; my ( $template_file_name, $templateText, %hash ) = ''; my @vars = split "\n", <<END; ##location## ##rtrname## ##loop0-ip## ##frame-ip## ##frame-DLCI## ##eth0-ip## END while (<>) { chomp; my @fields = split /,/; my $templateFN = pop @fields; if ( $template_file_name ne $templateFN ) { $template_file_name = $templateFN; undef $templateText; } @hash{@vars} = @fields; $templateText //= getTemplateText($template_file_name); my $templateTextCopy = $templateText; $templateTextCopy =~ s/$_/$hash{$_}/g for keys %hash; my $ofile_name = $hash{'##rtrname##'} . '.txt'; open my $fh, '>', $ofile_name or die "$ofile_name: $!"; print $fh $templateTextCopy; close $fh; } sub getTemplateText { my ($template_file_name) = @_; local $/; open my $fh, '<', $template_file_name or die "$template_file_name: + $!"; $templateText = <$fh>; close $fh; return $templateText; }
The last CSV column needs to contain the template's file name. The script can handle multiple files at once, e.g.:
processCSV.pl csv1.csv csv2.csv
The script uses Perl's 'defined-or-equals' operator to only read the template's text once, and will read in a new template if it detects a change in the template's file name (e.g., when going from csv1.csv to csv2.csv).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: Processing CSV File
by Anonymous Monk on Oct 05, 2012 at 00:44 UTC | |
by Kenosis (Priest) on Oct 05, 2012 at 01:13 UTC | |
by Perl3r (Novice) on Oct 05, 2012 at 02:38 UTC | |
by Kenosis (Priest) on Oct 05, 2012 at 04:45 UTC | |
by Anonymous Monk on Oct 05, 2012 at 04:58 UTC | |
|