Given the input string 'hello boss!,where are you?,"how, are you!",hi,"di chellam","welcome"' our objective is to design a Perl program that intelligently separates and extracts each individual word from the CSV-like structure. The complexity lies in correctly handling quoted content containing commas.
CODE:
use strict;
use strict;
use warnings;
my $input_string = 'hello boss!,where are you?,"how, are you!",hi,"di chellam","welcome"';
# Initialize empty array to store extracted words
my @words = ();
# Use a while loop with a regex to extract words
while ($input_string =~ /((?:(?<=,)|^)\s*"[^"]*"\s*(?=,|$)|[^,]*),?/g) {
my $word = $1;
# Remove leading and trailing spaces
$word =~ s/^\s+|\s+$//g;\
# Check if the word is quoted
if ($word =~ /^\"(.*)\"$/) {
# Extract the word without the quotes
my $quoted_word = $1;
# Add the word to the array
push @words, $quoted_word;
} else {
# Add the word to the array
push @words, $word;
}
}
# Print the extracted words
print join("\n", @words), "\n";
Read more »Labels: perl csv, perl problems