Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Processing CSV File

by choroba (Abbot)
on Oct 03, 2012 at 07:55 UTC ( #996999=note: print w/ replies, xml ) Need Help??


in reply to Processing CSV File

This works for me:

#!/usr/bin/perl use warnings; use strict; open my $TEMPLATE, '<', 'rtr-template.txt' or die "Template: $!"; my @template = <$TEMPLATE>; while (<>) { chomp; my ($location, $name, $lo0ip, $frameip, $framedlci, $eth0ip) = split (/,/); my $ofile_name = $name . ".txt"; open my $OUT, '>', $ofile_name or die "Output: $!"; for my $line (@template) { $_ = $line; s/##location##/$location/; s/##rtrname##/$name/; s/##eth0-ip##/$eth0ip/; s/##loop0-ip##/$lo0ip/; s/##frame-ip##/$frameip/; s/##frame-DLCI##/$framedlci/; print {$OUT} $_; } }
The important changes I made to your code:
  • 3-argument version of open is used.
  • Lexical filehandles are used ($FH instead of FH).
  • I am using strict.
  • The template file is not changing, so it is opened and read just once.
  • chomp is used to remove the newline from $eth0ip.
  • print is used instead of printf: using printf without a format string is useless.
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ


Comment on Re: Processing CSV File
Select or Download Code
Re: Processing CSV File
by Perl3r (Initiate) on Oct 03, 2012 at 23:21 UTC

    Thank you all, you have been extremely helpful!! I have found another problem, and that is with the CSV file.. The CSV will need to be a spreadsheet maintained in MS Excel.. The problem with that is, that when the CSV is saved in excel, it adds a hidden CR at the end of each line, so when the script runs, it fails after reading the first line.. Is it possible to amend the script above to ignore that CR?, or I am better off doing some pre processing to the CSV file to remove the CR? Thanks again!!

      Instead of chomp, use s/\r\n//.
      لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://996999]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (9)
As of 2014-09-02 09:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (21 votes), past polls