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

I have returned a .csv like file using WWW::Mechanize.
use warnings; use strict; use WWW::Mechanize; use DBI; # Assign url strings; my $first_url = 'http://www.ots.treas.gov/holdsq/hold.cfm?catNumber=61 +&firstview=1'; # Fetch the page $mech->get($first_url); # Submit the SelectMenu form blankly $mech->submit_form( form_name => 'SelectMenu', fields => { CATNUMBER => '61', docket => '', hcno => '', hcn1 => '', hrg => '', state => '', zip => '', ptt => '', status => '', bank => '', date_from => '', date_to => '', eff_from => '', eff_to => '' } ); # Now $mech has the returned page. Will submit the form to get the cs +v file $mech->submit_form ( form_name => 'getCSV', fields => { CATNUMBER => '61', DOCKET => '', HCNO => '', HCN1 => '', HRG => '', STATE => '', ZIP => '', PTT => '', STATUS => '', BANK => '', DATE_FROM => '', DATE_TO => '', EFF_FROM => '', EFF_TO => '' } ); # Now $mech has a reference to all the thrift holding companies # In .csv format. my $content = $mech->content;
I would like to go through $content line by line, but I don't know where to start. Any help would be great.

Replies are listed 'Best First'.
Re: 'Looping' through a variable
by ikegami (Patriarch) on Aug 30, 2007 at 22:06 UTC

    Since Perl 5.8, scalars can be used as file buffers. This is useful if your CSV modules requires a file handle. (I used Text::CSV which does not.)

    use Text::CSV qw( ); my $content = ...; my $csv = Text::CSV->new(); open my $csv_fh, '<', \$content; while (<$csv_fh>) { my $status = $csv->parse($_) or die; my @fields = $csv->fields(); ... }

    If you don't require a file handle, it's simple to extract lines yourself.

    use Text::CSV qw( ); my $content = ...; my $csv = Text::CSV->new(); while (length($content)) { my ($line) = $content =~ s/^([^\r\n]*)\r?\n?//; my $status = $csv->parse($line) or die; my @fields = $csv->fields(); ... }

    Update: Added second snippet. Allowed for \r\n.