Dear Monks,
This problem has been bothering me for some time. It feels like it should be possible, but I don't know where to begin.
I have some text data - a csv file for example. I have a subroutine that can parse csv data, say csvparse(). How can I make csvparse() smart so that it can accept csv data from a string passed as a scalar, from a filehandle, or from a file without slurping in the entire file (except in the scalar case, of course) and without making three separate subs - one for each data type? Is this possible?
Here is some stumbling in the dark...
#!/usr/bin/perl -w
use strict;
use CGI;
{
# case 1 - a file
my $file = "csvfile.csv";
my %parseddata = csvparse($file);
}
{
# case 2 - a filehandle
my $uploadedfile = param('uploadfile');
my %parseddata = csvparse($uploadedfile);
}
{
# case 3 - a scalar
my $csvdata = 'first,middle,last,phone,email';
my %parseddata = csvparse($csvdata);
}
# so how can I avoid having three separate csv parsing subs?
# Once it can get at the data, the parsing is the same for all 3 cases
+!
sub csvparse {
my $data = $_[0];
if (ref($data) eq 'SCALAR') {
for (split(/\n/,$data)) {
# parse...
}
} elsif (-f "$data") {
open(DATA, "$data") or die("Noooo!\n");
while (<DATA>) {
# parse...
}
close(DATA);
} elsif () { # detect filehandle???
}
}
yuck.
Thanks
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.