3

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.

4 Answers 4

9

Use split:

@a = split(/\|/, $var);
Sign up to request clarification or add additional context in comments.

Comments

0

You want to use split

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

1 Comment

Alas, this will print a, because split treats the pattern as a regexp and | is a regexp metacharacter. (The regexp | matches either the empty string or the empty string, which is kind of silly but technically a valid regexp.) To fix it, you should quote the | like Mat shows. Also, please test your code before posting it.
0

Although I'm not quite sure what you intend to do, but it seems to me like you're trying to solve a problem on your own which has already a solution?!

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

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

Comments

-2

you can use the regex like this

$var=~s/(\w+|\d+)/$data[$gg++]=$1;''/eg;

now the array @data holds the scalar data in $var...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.