Tuesday, January 15, 2013

Perl - Split a string into individual character array

How to split a string into individual characters and store in an array in Perl? Let us see in this article how to split a string 'welcome' into separate characters.

1. Using the split function:
my $x='welcome';
my @arr=split (//, $x);
print "@arr";
    The split function is used to split the string $x by giving the delimiter as nothing.  Since the delimiter is empty, split splits at every character, and hence all the individual characters are retrieved in the array.
  On running the above snippet, the result produced will be:
w e l c o m e
2. Using the pattern matching with a Regular Expression:
my $x='welcome';
my @arr=$x=~/./g;
print "@arr";
 The meta-character dot(.) matches a single character.  And hence, the above regular expression matches every character and is collected in the array "arr".

3. Using the substr function:
my $x='welcome';
my @arr=();
foreach (0..length($x)-1){
        push @arr, substr($x,$_,1);
print "@arr";
   This is the normal way of splitting a string into invidual characters using the substr function though not a recommended one. Using the substr function, every character is fetched and the element is added to the array "arr". This array, at the end of parsing the entire string, contains all the characters.
Note: $_ is a special scalar variable of Perl which contains the value being worked upon in the iteration.

No comments:

Post a Comment