user2986175
user2986175

Reputation: 337

Split is not working (Perl)

I have been trying to execute the following code; however @ans ends up with the entire contents of $answer in it.

$answer = "6.9 4012 top 5.6 2868 top 5.0 3686 top 4.7 5128 top 4.5 3120 top";
@ans = split('/ /',$answer);
foreach (@ans) {
    print "$_\n";
}

In this case I want to split based on white spaces. Please could you tell me what is wrong with this code?

Upvotes: 5

Views: 3720

Answers (4)

Thiyagu ATR
Thiyagu ATR

Reputation: 2264

Refer the below mentioned code,You have to use only one backslash to escape whitespace character.There is not necessary to enclose the whitespace with two backslash,if you specified this in side quotation

my $answer = "6.9 4012 top 5.6 2868 top 5.0 3686 top 4.7 5128 top 4.5 3120 top";
my @ans = split(" ",$answer);
# my @ans = split("\ ",$answer);
# my @ans = split(' ',$answer);
# my @ans = split('\ ',$answer);
# my @ans = split(/ /,$answer);
foreach (@ans) {
    print "$_\n";
}

Upvotes: 0

blio
blio

Reputation: 483

The mvp's answer is right. But I think that you may not understand the enclosing // meaning. It means matching the string in the enclosing //. So you do not need to quote the enclosing in your program like '/ /'. the document is here. split document

Upvotes: 0

mvp
mvp

Reputation: 116427

You use split incorrectly. This will work:

@ans = split(' ', $answer);

as well as this:

@ans = split(/ /, $answer);

Note that first parameter for split is not a string, but a regular expression. All variants for split expression below give identical result:

' ', / /, " ", m/ /, m' ', qr/ /, qr' ', qr{ }.

Usage of /str/ for regex is somewhat similar to match regex usage in expression:

my ($x) = ($str =~ /(w+)/);

or

my ($x) = ($str =~ m/(w+)/);

UPDATE: Thanks to @mpapec, there is one gotcha about ' ' vs / / from perldoc -f split:

As a special case, specifying a PATTERN of space (' ') will split on white space just as "split" with no arguments does. Thus, "split(' ')" can be used to emulate awk's default behavior, whereas "split(/ /)" will give you as many initial null fields (empty string) as there are leading spaces.

In other words, split(' ', " x y ") returns ('x', 'y'), but split(/ /, " x y ") returns ('', 'x', 'y').

Upvotes: 6

Jigar
Jigar

Reputation: 300

You can also use below lines to handle multiple spaces

@ans = split(/ +/,$answer);

Hope this might help you

Thanks

Upvotes: 0

Related Questions