Free Perl Tutorials

Split() in PERL

This tutorial teaches you how to use a very handy function in PERL called the split function. PERL allows you to split up a string into individual values if you would so choose.

Here is the format for using the split function in PERL. Formatting is very important to ensure the function works properly. (Feel free to copy and paste this to a notepad, save the file as a .pl file, and then run it from your command prompt)

#First we define a string
$mystring = "This is my wonderful string";

#Next we incorporate the split function to divide the string at each space
#We have five words, so we'll create 5 new variables
($v1,$v2,$v3,$v4,$v5) = split(/ /,$mystring);

#Now we print our code to check our results (the "/n" creates a new line)
print "$v1\n"
print "$v2\n"
print "$v3\n"
print "$v4\n"
print "$v5\n"




Here's what's happening:
In our first line, we have set a string variable.

In the second line, we create 5 new variables ($v1-$v5) and set these equal to each word split from our string. We do this between the "//" characters. Since we want the split function to split the data at each space, we place a space between the "//" characters.

I found this very useful video of how to do it on youtube: