存储架构

Perl – Split a string into individual character array

微信扫一扫,分享到朋友圈

Perl – Split a string into individual character array
0

H
ow 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.

阅读原文...


Avatar

Discipline

上一篇

2013 Resolution: More Free SlideRocket EDU Accounts

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Perl – Split a string into individual character array

长按储存图像,分享给朋友