Roguebantha
Roguebantha

Reputation: 824

Split values from variable into two fields

I have a variable that has two values in it separated by a semicolon. I want to get one of these values into one variable, and the other into another variable. I'm trying to do so using:

my $firstField = `echo $line | awk -F; '{print $1}'`;

But it's getting interpreted extremely oddly. How best would I do this?

Upvotes: 1

Views: 57

Answers (2)

T G
T G

Reputation: 501

You can get as many as you want with one split call: if you want them in scalar variables, use

    my ($a, $b) = split(";", $inputstring); # add $c, $d, etc as you like to the list

or to get a variable number into an array use:

    my @parts = split(";", $inputsring);

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74685

There is absolutely no need to involve any external tool here. Use perl!

my $firstField = (split(/;/, $line))[0];

The outer parentheses are required because of Perl's rule "If it looks like a function call, it's a function call". Without the extra parentheses, The [0] is interpreted as a subscript of the function call (which is invalid), rather than as a subscript of the list that is returned.

Or if you prefer:

my ($firstField) = split /;/, $line;

This assigns the first value of the list returned by split to the variable.

Upvotes: 4

Related Questions