开发者

Cutting apart string in Perl

I have a string in Perl that is 23 digits long. I need to cut it apart into different pieces. First 2 digits in one variable, next开发者_如何学Python 3 in another variable, next 4 into another variable, etc. Basically the 23 digits needs to end up as 6 separate variables (2,3,4,4,3,7) characters, in that order.

Any ideas how I can cut the string up like this?


There are lots of ways to do it, but the shortest is probably unpack:

my $string = '1' x 23;
my @values = unpack 'A2A3A4A4A3A7', $string;

If you need separate variables, you can use a list assignment:

my ($v1, $v2, $v3, $v4, $v5, $v6) = unpack 'A2A3A4A4A3A7', $string;


Expanding on Alex's method, rather than specify each start and end, use the list you gave of lengths.

#!/usr/bin/env perl

use strict;
use warnings;

my $string = "abcdefghijklmnopqrstuvw";
my $pos = 0;
my @split = map { 
  my $start = $pos; 
  my $end = $_;
  $pos += $end;
  substr( $string, $start, $end);
} (2,3,4,4,3,7);

print "$_\n" for @split;

This said you probably should look at unpack which is used for fixed width fields. I have no experience with it though.


You could use a regex, viz:

$string =~ /\d{2}\d{3}\d{4}\d{4}\d{3}\d{7}/

and capture each part by surrounding with brackets ().

You then find each capture in the variables $1, $2 ... or get them all in the returned list

See perldoc perlre


You want to use perldoc substr.

$substring = substr($string, $start, $length);

I'd also use `map' on a list of [start, length] pairs to make your life easier:

$string = "123456789";
@values = map {substr($string, $_->[0], $_->[1])} ([1, 3], [4, 2] , ...);


Here's a sub that will do it, using the already discussed unpack.

sub string_slices { 
    my $str = shift;
    return unpack( join( 'A', '', @_ ), $str );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜