I want to split a line based on multiple character lengths and store them in separate variables.
For ex:$myString = "Mickey 24 USA alive
Here first 12 characters are username, next 2 are age, next 23 characters are country and next 7 are status.
So is there a way to save them separately store them using split() or s///?
Thanks,
Unpacking fixed-width fields is most simply and efficiently done using the unpack built-in function.
Like this
use strict;
use warnings;
my $my_string = 'Mickey 24 USA alive';
my ($username, $age, $country, $status) = unpack 'a12 a2 a23 a7', $my_string;
print <<__END_OUTPUT__;
"$username"
"$age"
"$country"
"$status"
__END_OUTPUT__
output
"Mickey "
"24"
" USA"
" alive"
Use a regex to match, or a substr:
my $myString = "Mickey 24 USA alive";
if ($myString =~ /(.{12})(.{2})(.{23})(.*)/) {
$name = $1;
$age = $2;
$country = $3;
$status = $4;
print "<$name><$age><$country><$status>";
} else {
warn "line not long enough";
}
Outputs:
<Mickey ><24>< USA>< alive>
To strip spacing from the variables after the fact, just use another regex:
$value =~ s/^\s+|\s+$//g;
Can even do that in a single line using:
s/^\s+|\s+$//g for ($name, $age, $country, $status);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With