Philip Alex
Philip Alex

Reputation: 21

Splitting a string having comma separated and a text qualifier using perl

I need to split the below string using the perl, the details are given below. I need to load the data to a table from the CSV file. The string variables are enclosed in "". Please provide me an idea, I am new to perl scripting.

String : "February 6, 2012","","","1","02/06/12","","",1,1,0

output :

February 6, 2012
<BLANK VALUE>
<BLANK VALUE>
1
02/06/12
<BLANK VALUE>
<BLANK VALUE>
1
1
0

Upvotes: 2

Views: 1647

Answers (3)

edem
edem

Reputation: 3272

#!/usr/bin/perl
use strict;
use warnings;

my $ac = qq("February 6, 2012","","","1","02/06/12","","",1,1,0);

$ac=~s/\"//ig;
my @arr = split(',', $ac);
$arr[0] .= $arr[1];
print $arr[0] . "\n"; # the date is February 6, 2012

# print other elements
for (my $i=2; $i < @arr; $i++) {
    if ($arr[$i] eq '') {print "<BLANK VALUE>\n";}
    else {print $arr[$i] . "\n";}
}

Upvotes: 0

Rustem
Rustem

Reputation: 326

You can use regular expressions to split it. Each item that you want to split should be wrapped in a group, like this

^\"(.*?)\",\"\",\"\",\"(.*?)\",\"(.*?)\",\"\",\"\",(\d),(\d),(\d)

expression in the bracket it's a group, then you can get groups in code.

Upvotes: 0

user507077
user507077

Reputation:

This looks a lot like CSV. If it is then please do yourself and us a favor and use an appropriate module for it instead of regular expressions. There is the excellent Text::CSV_XS.

Upvotes: 8

Related Questions