Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split is not working (Perl)

Tags:

regex

split

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?

like image 293
user2986175 Avatar asked Dec 19 '13 09:12

user2986175


People also ask

How to split with in Perl?

Perl | split() Function. split() is a string function in Perl which is used to split or you can say to cut a string into smaller sections or pieces. There are different criteria to split a string, like on a single character, a regular expression(pattern), a group of characters or on undefined value etc..

How to split string by space in Perl?

How can we split a string in Perl on whitespace? The simplest way of doing this is to use the split() function, supplying a regular expression that matches whitespace as the first argument.


1 Answers

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').

like image 101
mvp Avatar answered Nov 08 '22 08:11

mvp