user2827740
user2827740

Reputation: 87

How to split with '|' in perl

the problem is that it return like split on undefined value

B
e
c
k
y
.

split string perl code

sub start_thread {
my @args = @_;
print('Thread started: ', @args, "\n");
open(my $myhandle,'<',@args) or die "unable to open file";  # typical open call
my @aftersplit;
for (;;) {
    while (<$myhandle>) {
    chomp;
    @aftersplit = split('|',$_);
    #print $_."\n";
    foreach my $val (@aftersplit){
       print $val."\n";
        }
    }
    sleep 1;
    seek FH, 0, 1;      # this clears the eof flag on FH
}
}

it split the string in $_ and save in array aftersplit

Upvotes: 1

Views: 673

Answers (3)

hwnd
hwnd

Reputation: 70732

You need to escape your delimiter, since it's a special character.

For certain special characters you need to precede your character with a literal \

my @aftersplit = split '\|', $_;

You can also use quotemeta.

my $separator = quotemeta('|');
my @aftersplit = split /$separator/, $_;

Or implement the escape sequence \Q

my @aftersplit = split /\Q|/, $_;

Upvotes: 2

jkshah
jkshah

Reputation: 11713

You need to escape special character | with \

@aftersplit = split('\|',$_);

Upvotes: 3

mpapec
mpapec

Reputation: 50647

You have to escape | as it is special char in regex,

my @aftersplit = split(/\|/, $_);

Upvotes: 3

Related Questions