perl

Convert variable into array


I have a requirement to send my variable to array. I have something like this:

var = "abc|xyz|123";

I want to have the above values in an array.

$arr[0]="abc";
$arr[1]="xyz";
$arr[2]="123";

I used the following way, but I am not getting the array size while using this way:

$var = "abc|xyz|123";
$var =~ tr/|/\n/; # transforming "|" to new line "\n"
@a = $var;
print $a[0];

The complete transformed output is sent to only variable instead of individual variables.


Solution

  • Use split:

    @a = split(/\|/, $var);