Convert variable to array in perl

I have a requirement to send my variable to an 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 method, but at the same time I do not get the size of the array

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

Full converted output is sent only to the variable instead of the individual variables.

Please help me with this.

Regards, Shriharsha Kalluru.

+3
source share
3 answers

Use split:

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

Although I'm not quite sure what you are going to do, it seems to me that you are trying to solve the problem yourself, which already has a solution?

This should do the trick: Using split () for Perl ?

 my $data = 'Becky Alcorn,25,female,Melbourne';
 my @values = split(',', $data);
0
source

Do you want to use split

$var = 'abc|xyz|123';
@a = split '|', $var;
print $a[0];
0
source

All Articles