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";
Share:
17,793

Related videos on Youtube

AgA
Author by

AgA

(your about me is currently blank)

Updated on June 04, 2022

Comments

  • AgA
    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
      Robert P about 13 years
      Another 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
      tchrist about 13 years
      use substr, but be careful to grab entire graphemes instead of single code points.
    • ysth
      ysth about 13 years
      the function you need is called substr (with a length of 1): substr(STRING, INDEX, 1)
  • AgA
    AgA about 13 years
    Thanks 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
    ikegami about 13 years
    @user656848, substr("abcd", 1, 1)
  • ikegami
    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
    AgA about 13 years
    Sorry to_arr($str)[2] should be to_arr($str)[1]. Thanks for pointing out.
  • AgA
    AgA about 13 years
    @ikegami substr("abcd",1,1) is better and simple
  • mu is too short
    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
    AgA about 13 years
    It could be any index and not just index 2.
  • AgA
    AgA about 13 years
    I 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
    ikegami about 13 years
    @user656848, Again, to_arr($str)[1] won't work. You'd need ( to_arr($str) )[1].
  • Lawrence Hutton
    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
    AgA about 13 years
    I'll go by substr("abcd",1,1)

Related