Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl-How to split a line based on different length of characters

Tags:

split

perl

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,

like image 659
james2611nov Avatar asked Jan 22 '26 15:01

james2611nov


2 Answers

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"
like image 62
Borodin Avatar answered Jan 24 '26 07:01

Borodin


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);
like image 30
Miller Avatar answered Jan 24 '26 07:01

Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!