Perl split Function

The Perl split function splits a string into an array. A string is splitted based on delimiter specified by pattern. By default, it whitespace is assumed as delimiter.

Syntax
Split /pattern/, variableName
Example

In this example, split returns a list of strings. The delimiter is (-). It means string is splitted at (-).

snippet
my $str = "Cu-K-Na-Hg-Pb-Li";  
my @break = split /-/, $str;  
print "@break\n";
Output
Cu K Na Hg Pb Li

Limit number of parts

We can limit the number of parts to be splitted for a string.

Example

In this example, string splits in 3 parts.

snippet
my $str = "Cu-K-Na-Hg-Pb-Li";  
my @break = split(/-/, $str, 3);  
print "@break\n";
Output
Cu K Na-Hg-Pb-Li

split on Multiple Characters

We can split a character at more than one delimiter. In the following example, we have split the string at (=) and (,).

  1. my $str = 'Vishal=18Sept,Anu=11May,Juhi=5Jul';
  2. my @words = split /[=,]/, $str;
  3. print "@words\n";
Output
Vishal 18Sept Anu 11May Juhi 5Jul

As they are key-value pairs, we can assign the result into a hash instead of an array.

  1. use Data::Dumper qw(Dumper);
  2. my $str = 'Vishal=18th Sept,Anu=11th May,Juhi=5th Jul';
  3. my %words = split /[=,]/, $str;
  4. print Dumper \%words;
Output
$VAR1 = ( 'Anu', => '11th May', 'Vishal', => '18th Sept', 'Juhi', => '5th Jul', );

split on Empty String

Split on empty string means the string will split at every place where it will find an empty string. There is an empty string, between every two characters. It means it will return the original string split into individual characters.

  1. my $str = "rookienerd";
  2. my @break = split //, $str;
  3. print "@break\n";
Output
J A V A P O I N T

join Function

Perl join character, joins elements into a single string using a delimiter pattern to separate each element. It is opposite of split.

Syntax
join 'pattern', variableName
Example

In the following example, we have joined in three different ways.

First, we are joining (:) in between each elements of array.

Second, we will join (- vowels) with the output of first one.

Third, we added two more characters in the original array.

  1. my @vowels = ('A', 'E', 'I');
  2. my $str = join ':', @vowels;
  3. print "$str\n";
  4. my $data = join "-", $str, "vowels";
  5. print "$data\n";
  6. $str = join '', @vowels, 'OU';
  7. print "$str\n";
Output
A:E:I A:E:I -vowels AEIOU
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +