What is the shortest way to convert string characters into an array of characters in Perl?
17,793
Solution 1
my @arr = split //, "abcd";
my @arr = "abcd" =~ /./sg;
my @arr = unpack '(a)*', 'abcd';
Solution 2
The simplest way is with split with a regex that matches anything.
my @arr = split //, "abcd";
Related videos on Youtube
Comments
-
AgA almost 2 years
If I've the string "abcd", what's the shortest way to convert in @arr containing qw(a b c d)?
-
Robert P about 13 yearsAnother question might be why do you need to split a string of characters into an array of characters? For most things in other languages that require an array of characters, there's a single function that sidesteps that need in Perl.
-
tchrist about 13 yearsuse substr, but be careful to grab entire graphemes instead of single code points.
-
ysth about 13 yearsthe function you need is called substr (with a length of 1):
substr(STRING, INDEX, 1)
-
-
AgA about 13 yearsThanks but if I want 2nd char in the string "abcd" then I'd be writing in an expression: ((split //."abcd")[1]). Could it be simpler than this? In case of a function: to_arr($str)[2] may be bit shorter?
-
ikegami about 13 years@user656848,
substr("abcd", 1, 1)
-
ikegami about 13 years@user656848,
to_arr($str)[2]
isn't valid and uses the wrong index. You'd need( to_arr($str) )[1]
. It's called a "list slice". -
AgA about 13 yearsSorry to_arr($str)[2] should be to_arr($str)[1]. Thanks for pointing out.
-
AgA about 13 years@ikegami substr("abcd",1,1) is better and simple
-
mu is too short about 13 years@user656848: If you just want the second character then why are you asking how to convert a string into an array of characters?
-
AgA about 13 yearsIt could be any index and not just index 2.
-
AgA about 13 yearsI need to extract a char in an expression. Then I'll need to do lot of wrapping in parantheses as in your example Colin. I think using a function like to_arr($str)[index] will be simpler.
-
ikegami about 13 years@user656848, Again,
to_arr($str)[1]
won't work. You'd need( to_arr($str) )[1]
. -
Lawrence Hutton about 13 years@user656848: You can get a single character at any index without turning the string into an array by using
substr
. This will also be much more efficient than chopping the string up, storing the individual characters in memory, and then throwing all but one of them away. -
AgA about 13 yearsI'll go by substr("abcd",1,1)