superzero10 superzero10 - 2 months ago 7
Perl Question

Split to get only characters in Perl

I have a string like this :

Reporting EXE1 BASE,Normal


I need to get a var for every words like :

$info = "Reporting";
$host = "EXE1";
$device = "BASE";
$status = "Normal";


In fact, i saw the function "Split" might be a good use, but i don't understand the patern to use.

Answer

You might try this code.

my $str = "Reporting EXE1 BASE,Normal";
my @fields = split /\s|,/, $str;
my $info = $fields[0];
my $host = $fields[1];
my $device = $fields[2];
my $status = $fields[3];
print "$info\n";
print "$host\n";
print "$device\n";
print "$status\n";

Or more compact version -

my $str = "Reporting EXE1 BASE,Normal";
my ( $info, $host, $device, $status ) = split /[\s,]/, $str ;
print "$info\n";
print "$host\n";
print "$device\n";
print "$status\n";