CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner: Re: [gouse.aman] SAving data to a CSV file: Edit Log


May 2, 2013, 6:59 PM

Views: 1263
Re: [gouse.aman] SAving data to a CSV file

Please consider being more explanatory next time. By data do you mean just data you are supplying or data from another text/file that you want to save to CSV? Also the user asked for a better option in perl, by no means I am saying your code is wrong, but I would just address what is asked more politely.


open(CSV, ">D:\check.csv");
print CSV "NAME\tSEX\tAGE\n";
print CSV "Anbu\tMale\t20\n";
print CSV "Akilan\tMale\t22\n";

I would write this as so if you just want to use a simple save.

open my $fh, '>', 'check.csv' or die $!;
print $fh "name\tsex\tage\n";
close $fh;

You are probably wondering what is my? Well my creates a new lexical variable. The variable only exists until the innermost enclosing block of code is exited. To start I would read perl documentation on lexical variables for more of a explanation.

For a more simple and better method I would suggest using CPAN's module Text::CSV.

Here is an example of how you could do this:

use strict;
use warnings;

use Text::CSV;

my @rows = qw(name age sex);

my $csv = Text::CSV->new ( { binary => 1, eol => "\n" } )
or die "error: ".Text::CSV->error_diag ();

open my $fh, '>', 'check.csv' or die $!;
$csv->print( $fh, $_ ) for @rows;
close $fh;

(This post was edited by hwnd on May 2, 2013, 7:19 PM)

Edit Log:
Post edited by hwnd (User) on May 2, 2013, 7:19 PM

Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives