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

I have a file that i have to read...the data is delimited by string 'chr(9)' sample data

DataAchr(9)DataBchr(9)DataC

i want to use split function to put this into an array...

if i do the following i get an error...here's my code

open (OBFILE, 'outbound.txt'); open (OBout, '>outbound_output.txt'); while (<OBFILE>) { chomp; $re = 'chr(9)'; @array= split(/$re/,$_); #print OBout "$date\t$time\t$ani\t$entid\n"; print "@array\n"; } close(OBFILE); close(OBout);

Replies are listed 'Best First'.
Re: split() help
by GrandFather (Saint) on Jan 24, 2008 at 00:30 UTC

    '(' and ')' are magic characters in a regex so need to be quoted if you want a literal match for them. One way to do it is use the quote meta sequence. Consider:

    use strict; use warnings; my $data = <<DATA; DataAchr(9)DataBchr(9)DataC DATA open my $infile, '<', \$data; while (<$infile>) { chomp; my $re = 'chr(9)'; my @array= split(/\Q$re\E/,$_); print "@array\n"; } close $infile;

    Prints:

    DataA DataB DataC

    Perl is environmentally friendly - it saves trees
Re: split() help
by runrig (Abbot) on Jan 24, 2008 at 00:17 UTC
    Check the status of the file opens....always open(....) or die "Couldn't open file: $!" or something similar.

    Update: (after listening to CB chatter) Oh. You need to escape the parens in the regex. But you know that now (though you should still check the status of file opens) :-)

Re: split() help
by Anonymous Monk on Jan 24, 2008 at 01:30 UTC
    just in case you actually want to  split on a single character with the value of 9 decimal ( \t, a horizontal tab) and not on the six character string indicated in your OP, remove the single-quotes from the  chr(9) in the assignment, i.e.

    $re = chr(9);

    and follow suggestions of the other respondents.

Re: split() help
by chrism01 (Friar) on Jan 24, 2008 at 06:11 UTC
    If those are real tabs, then split on \t
    # split tab $var1="asd zxc ggg"; @arr1=split(/\t/, $var1); print "@arr1\n";
    works for me, where those 'spaces' in $var1 are actually tabs.

    Cheers
    Chris