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.. The best thing about this function that user can specify how many sections to split the string into.
Syntax:
split /Pattern/, Expression, Limit
or
split /Pattern/, Expression
or
split /Pattern/
or
Split
In the above syntax,
Pattern is specified a regular expression which provides the criteria to split the string. The
Expression is the string which is to be split. The
Limit is kind of restriction which stops the splitting at (n-1)th pattern found in the string.
Return Value: This method returns the value in
two context as follows:
In Array Context: Here it returns a list of the fields which found in Expression. If no Expression is specified then it returns $_.
In Scalar Context: Here it returns the number of fields which found in Expression and then stored the fields in the @_ array.
There are
different ways to use split() Function as follows:
- Splitting on a Character
- Splitting among a String without Limit
- Splitting among a String with Limit
- Splitting on a Undefined value
- Splitting on a Regex(Pattern)
- Splitting on Hash
- Splitting on Space
Splitting on a Character
User can break or split the string on different characters like
comma(,) backslash(\) etc. This type of splitting is generally used when you have to parse the data from another program or a file. Don't use split() to parse the
CSV(comma separated value) files. If there are commas in your data then use
Text::CSV instead.
Example:
Perl
# Perl program to demonstrate the splitting on character
#!/usr/bin/perl
use strict;
use warnings;
# Here character is comma(, )
my $str = 'Geeks, for, Geeks';
# using split() function
my @spl = split(', ', $str);
# displaying result using foreach loop
foreach my $i (@spl)
{
print "$i";
}
Splitting among String without any Limit
This also works same as the splitting on the character. Here string's data is separated by two
!!.
Example:
Perl
# Perl program to demonstrate the
# splitting among string without Limit
#!/usr/bin/perl
use strict;
use warnings;
# string which is separated by !! sign
my $str = 'GFG!!Geeks!!55!!GeeksforGeeks';
# using split function without Limit
my @spl = split('!!', $str);
# displaying string after splitting
foreach my $i (@spl)
{
print "$i\n";
}
Output:
GFG
Geeks
55
GeeksforGeeks
Splitting among String with Limit
This also works same as the splitting on the character. Here string's data is separated by two
!!. Here the user can restrict the number of sections the string will split into by passing the third argument in split function which will be a positive integer value. In below example user pass the
Limit as 3 so it will restrict the splitting of the string into 3, even there are the 4 occurrences of
!! in the string.
Example:
Perl
# Perl program to demonstrate the
# splitting on string with Limit
#!/usr/bin/perl
use strict;
use warnings;
# string which is separated by !! sign
my $str = 'GFG!!Geeks!!55!!GeeksforGeeks';
# using split function with Limit
my @spl = split('!!', $str, 3);
# displaying string after splitting
foreach my $i (@spl)
{
print "$i\n";
}
Output:
GFG
Geeks
55!!GeeksforGeeks
Splitting on an undefined value
If the user will try to split on an undefined value, then the string will split on every character.
Example:
Perl
# Perl program to demonstrate the
# splitting on undefined value
#!/usr/bin/perl
use strict;
use warnings;
# string to be split
my $str = 'GeeksforGeeks GFG';
# using split function
my @spl = split(undef, $str);
# displaying string after splitting
foreach my $i (@spl)
{
print "$i\n";
}
Output:
G
e
e
k
s
f
o
r
G
e
e
k
s
G
F
G
Runtime Error:
Use of uninitialized value in regexp compilation at /home/38ececda726bcb7e68fb7b41eee5b8d9.pl line 12.
Splitting on a Pattern or Regex
Sometimes user may want to split the string on a pattern(regex) or a particular type of character. Here we will use the special character classes to make pattern of digits(integer) as follows:
Example:
Perl
# Perl program to demonstrate the
# splitting on a pattern(regex)
#!/usr/bin/perl
use strict;
use warnings;
# string to be split
my $str = 'Geeks1for2Geeks';
# using split function
# \d+ will match one or more
# integer numbers & placed
# between two //
my @spl = split(/\d+/, $str);
# displaying string after splitting
foreach my $i (@spl)
{
print "$i\n";
}
Splitting into a hash
A user can split the data or string into the hash instead of an array. Basically, a hash is a key/value pair. Before splitting user must have knowledge about the hashes.
Example:
Perl
# Perl program to demonstrate the
# splitting into the hash
#!/usr/bin/perl
use strict;
use warnings;
# hash to be split
my $has = 'GFG=1;GEEKS=2;PROGEEK=3';
# using split function
my %spl = split(/[=;]/, $has);
# after splitting displaying the values
foreach my $i (keys %spl)
{
print "$i:$spl{$i}\n";
}
Output:
GFG:1
GEEKS:2
PROGEEK:3
Splitting on Space
Here space doesn't mean only
' ' this space but it also includes the newline, tabs etc.
Example:
Perl
# Perl program to demonstrate the
# splitting on space
#!/usr/bin/perl
use strict;
use warnings;
# string to be splitted
my $str = "ProGeek\n\nSudo\nPlacements";
# using split function
my @spl = split(' ', $str);
# Displaying result by printing
# 'GFG' either side of the
# value, so that user can see
# where it split
foreach my $i (@spl)
{
print "GFG${i}GFG\n";
}
Output:
GFGProGeekGFG
GFGSudoGFG
GFGPlacementsGFG
Important Points To Remember
- As split() function also returns the value in scalar context. So for storing the return values user have to define some scalar values according to the number of sections of splitting. In below example there will be 4 values after splitting so here user will define the 4 scalars values and store the return values.
Example:
Perl
# Perl program to demonstrate the
# splitting on string and storing
# values in scalars
#!/usr/bin/perl
use strict;
use warnings;
# string which is separated by !! sign
my $str = 'GFG!Sudo!GeeksforGeeks!ProGeek';
# using split function and
# storing values in scalars
my ($sc1, $sc2, $sc3, $sc4) = split('!', $str);
# displaying string after splitting
print "$sc1\n$sc2\n$sc3\n$sc4";
Output:
GFG
Sudo
GeeksforGeeks
ProGeek
- There may be a situation when user don't pass in a string to split, then by default split() function will use the $_ and if user don't pass a Expression i.e. the string to split on then it will use ' '(a space).
Example:
Perl
# Perl program to demonstrate the
# split() function and context
#!/usr/bin/perl
use strict;
use warnings;
# using foreach loop containing string values
foreach ('G F G', 'Geeks for Geeks')
{
# using split() function
my @spl = split;
# displaying values to be split
print "Split $_:\n";
foreach my $i (@spl)
{
print " $i\n";
}
}
Output:
Split G F G:
G
F
G
Split Geeks for Geeks:
Geeks
for
Geeks
- If the delimiter is present at the starting of the string which is to be split, then the first element of return values will be empty and that will store into the array. In below example we have this situation and we are printing the empty value of resulted array:
Example:
Perl
# Perl program to demonstrate the
# split() function with the Delimiter
# at the start of the string
#!/usr/bin/perl
use strict;
use warnings;
# string containing delimiter(, )
# at the starting
my $str = ', GFG, Geeks';
# using split function
my @spl = split(', ', $str);
# printing "Array_Element: " with each
# returned value so that you can see
# the empty one
foreach my $i (@spl)
{
print "Array_Element: $i\n";
}
Output:
Array_Element:
Array_Element: GFG
Array_Element: Geeks
- If you want to keep the delimiter in result also then simply put that delimiter inside the parentheses.
Example:
Perl
# Perl program to demonstrate the
# split() function and keeping
# the delimiter
#!/usr/bin/perl
use strict;
use warnings;
# string to be split
my $str = 'Geeks1for2Geeks';
# using split function
# \d+ will match one or more
# integer numbers & placed
# between two // and () to
# keep the delimiter in result
my @spl = split(/(\d+)/, $str);
# displaying string after splitting
foreach my $i (@spl)
{
print "$i\n";
}
Output:
Geeks
1
for
2
Geeks
Similar Reads
Perl | sprintf() Function
sprintf() function in Perl uses Format provided by the user to return the formatted string with the use of the values in the list. This function is identical to printf but it returns the formatted string instead of printing it. Syntax: sprintf Format, List Returns: a formatted scalar string Example
1 min read
Perl | shift() Function
shift() function in Perl returns the first value in an array, removing it and shifting the elements of the array list to the left by one. Shift operation removes the value like pop but is taken from the start of the array instead of the end as in pop. This function returns undef if the array is empt
2 min read
Perl | sqrt() Function
Many times it happens that while solving mathematical expressions we require to calculate the square root of a number. To solve this issue, like other programming language Perl provides us with a built-in function sqrt() which can be used to calculate the square root of a number. Syntax: sqrt value
1 min read
Perl | unshift() Function
unshift() function in Perl places the given list of elements at the beginning of an array. Thereby shifting all the values in the array by right. Multiple values can be unshift using this operation. This function returns the number of new elements in an array. Syntax: unshift(Array, List)Returns: Nu
2 min read
Perl | substr() function
substr() in Perl returns a substring out of the string passed to the function starting from a given index up to the length specified. This function by default returns the remaining part of the string starting from the given index if the length is not specified. A replacement string can also be passe
2 min read
Perl | rindex() Function
rindex() function in Perl operates similar to index() function, except it returns the position of the last occurrence of the substring (or pattern) in the string (or text). If the position is specified, returns the last occurrence at or before that position. Syntax: # Searches pat in text from given
2 min read
Perl | values() Function
values() Function in Perl returns the list of all the values stored in a Hash. In a scalar context it returns the number of elements stored in the Hash. Note: Values returned from the value() Function may not always be in the same order. Syntax: values Hash Returns: list of values in the list contex
2 min read
Perl | splice() - The Versatile Function
In Perl, the splice() function is used to remove and return a certain number of elements from an array. A list of elements can be inserted in place of the removed elements. Syntax: splice(@array, offset, length, replacement_list) Parameters: @array - The array in consideration. offset - Offset of re
9 min read
Perl | oct() Function
oct() function in Perl converts the octal value passed to its respective decimal value. For example, oct('1015') will return '525'. This function returns the resultant decimal value in the form of a string which can be used as a number because Perl automatically converts a string to a number in nume
1 min read
Perl | abs() function
This function returns the absolute value of its argument. If a pure integer value is passed then it will return it as it is, but if a string is passed then it will return zero. If VALUE is omitted then it uses $_ Syntax: abs(VALUE) Parameter: VALUE: It is a required number which can be either positi
2 min read