1

I have this code below:

my $file = 'c:\test.log';
open (FILE, "<", $file) or die $!;
my @list = grep /\bAdobe\b/, <FILE>;
my $days;
foreach (@list) {
    $days = $_;
    print "$days\n";
}

Expected Result is:

"Adobe","10:10:10, 11/10/2011","Ready"

I want to split the result by comma with this code below:

my @sample = split(',', $days);

Expected Result is:

"Adobe"
"10:10:10
11/10/2011"
"Ready"

but it's not what I wanted to do.

I want to print the output like this:

"Adobe"
"10:10:10, 11/10/2011"
"Ready"

How could I achieve this without using/installing any module like Text::CSV?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
quinekxi
  • 879
  • 5
  • 14
  • 27

4 Answers4

6

Ideally, you would use a CSV parser, see Text::CSV. Or as long as all the fields are double quoted, then you can use a split with a slightly more complicated regex, which checks for the delimiters:

split /(?<="),(?=")/, $days;
a'r
  • 35,921
  • 7
  • 66
  • 67
4

I believe it's work for Text::CSV module. Something like this example should works:

use Text::CSV;

my $file = 'c:\test.log';
open (my $FILE, "<", $file) or die $!;
my $csv = Text::CSV->new;

while (my $row = $csv->getline($FILE)) {
  my @sample = @$row;
  next if $sample[0] !~ /\bAdobe\b/;
  # do whatever you want
}
yko
  • 2,710
  • 13
  • 15
  • Yes, I've already tried this one. But I am restricted not to use/install any module from cpan. – quinekxi Nov 22 '11 at 11:57
  • 2
    It's not mandatory to 'install', just download from cpan, extract and put "use lib 'path/to/text-csv/lib'" somewhere in head of your script. – yko Nov 22 '11 at 12:02
2

There's no need to install Text::CSV from CPAN (although, if you have that restriction then you really need to get that fixed) as the Text::ParseWords module from the standard distribution can be used too.

Dave Cross
  • 68,119
  • 3
  • 51
  • 97
1

Since the string "Adobe","10:10:10, 11/10/2011","Ready" is valid as perl code, you can use eval:

my $file = 'c:\test.log';
open my $fh, "<", $file or die $!;
for (grep /\bAdobe\b/, <FILE>) {
    my @sample = eval;
    # code here
}

But only do this for data you are sure is in a valid format.

Output from Data::Dumper:

$VAR1 = [
          "Adobe",
          "10:10:10, 11/10/2011",
          "Ready"
        ];
TLP
  • 66,756
  • 10
  • 92
  • 149