Split Function


P

perl Newbie

Hi,

I want to split text whenever there is a semi-colon. But my condition
is split function should ignore \; in line.
I have the following script to achieve the task. My query is
1. Is there a better way to do this or Is it possible to give
condition along with split
2. In the script if I use $_=~s/$ignore_txts[$i]/##/; instead of $_=~s/
\\;/###/; it replaces first occurrences of semi-colon instead of
replacing \;. I could not understand why is this happening?


DATA FILE
-------------------

*include q1.qin;col(a)=100;txt1=Ablah Ablah\; Bblah Bblah \; Cblah
cblah ;txt2=New Text;txt3=blah blah \; blah


SCRIPT
-------------------
use strict;
use warnings;

open(DATA,"< text") or die "Unable to open file\n";

my @normal_splits;
my @special_splits;
my @ignore_txts;
my $line;
while(<DATA>){
print "Text: $_\n";
@normal_splits=split(/;/,$_);

print "Texts after regular split function:\n";
foreach my $l(@normal_splits){
print $l, "\n";
}

if ($_=~/\\;/){
@ignore_txts = /(\\;)/g;
}
for (my $i=0;$i<$#ignore_txts+1;$i++) {
##$_=~s/$ignore_txts[$i]/##/;
$_=~s/\\;/###/;
}
print "$_\n";
@special_splits=split(/;/,$_);

print "Texts after replace\n";
foreach my $l(@special_splits){
$l=~s/###/\\;/g;
print $l, "\n";
}


}
close(DATA);


OUTPUT
-------------------

Text: *include q1.qin;col(a)=100;txt1=Ablah Ablah\; Bblah Bblah \;
Cblah cblah ;txt2=New Text;txt3=blah blah \; blah

Texts after regular split function:
*include q1.qin
col(a)=100
txt1=Ablah Ablah\
Bblah Bblah \
Cblah cblah
txt2=New Text
txt3=blah blah \
blah

*include q1.qin;col(a)=100;txt1=Ablah Ablah### Bblah Bblah ### Cblah
cblah ;txt2=New Text;txt3=blah blah ### blah

Texts after replace
*include q1.qin
col(a)=100
txt1=Ablah Ablah\; Bblah Bblah \; Cblah cblah
txt2=New Text
txt3=blah blah \; blah
 
Ad

Advertisements

Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top