Perl split string separated by special character

Hello

I have string (string can have more sections)

LINE="AA;BB;CC;DD;EE"

I would like to assigne each part of string separated by ";" to some new variable.

Can someone help?

This is especially convenient in perl as you can assign a list of variables to a list of results. split() like many things returns a list.

my ($a,$b,$c,$d,$e)=split(/;/,"a;b;c;d;e");

print "a is $a\n";
print "b is $b\n";

It won't arbitrarily declare new varibles, though. For an indeterminate number of results, use a list.

my @list=split(/;/, "a;b;c;d;e");

print @list[0], "\n";
1 Like

Hello vikus,

Not sure if I completly understood requirement, but could you please try following with awk and let me know if this helps.

echo $LINE | awk -F";" '{for(i=1;i<=NF;i++){print "VAR"_++j "=" $i}}

Output will be as follows. As of now it is doing print only we can use the same as variables too.

VAR0=AA
VAR1=BB
VAR2=CC
VAR3=DD
VAR4=EE

Following is the example for using like a variable.

echo $LINE | awk -F";" '{for(i=1;i<=NF;i++){A="VAr_"++j;;if(A=="VAr_3"){print $i}}}'

Output will be as follows.

CC

Thanks,
R. Singh

my @list=split(/;/, "a;b;c;d;e");

foreach my $val (@list) {
    print $val ;
}

I have someting like this, how to assigned to value this what is printed?

It already is assigned to something, otherwise you couldn't print it.