Perl切割字符串

时间:2014-07-20 07:32:06

标签: string perl substring substr

我有一个数字数组和字符串文件如下所示,我写下了一个名为string cutter的perl代码。我可以得到剪切的字符串,但我不能得到由数字数组所限定的第一个字符串。任何的想法?我不知道为什么substr不起作用。

string Cutter

file 1:

1234567890
0987654321
1234546789
ABCDEFGHIJ
JIHGFEDCBA

file 2: array of given length

2, 3, 4, 2, 1

Current Result:

34567890
7654321
546789
CDEFGHIJ
IHGFEDCBA

Supposed to be Result (perhaps \t delimited):
12 34567890
098 7654321
1234 546789
AB CDEFGHIJ
J IHGFEDCBA

我的代码:

#!/usr/bin/perl
use warnings;
use strict;

if (@ARGV != 2) {
    die "Invalid usage\n"
        . "Usage: perl program.pl [num_list] [string_file]\n";
}

my ($number_f, $string_f) = @ARGV;

open my $LIST, '<', $number_f or die "Cannot open $number_f: $!";
my @numbers = split /, */, <$LIST>;
close $LIST;

open my $DATA, '<', $string_f or die "Cannot open $string_f: $!";
while (my $string = <$DATA>) {
        substr $string, 0, shift @numbers, q(); # Replace the first n characters with an empty string.

        print $string;
}

非常感谢

1 个答案:

答案 0 :(得分:3)

perldoc -f substr:

Extracts a substring out of EXPR and returns it

所以你应该这样做:

    $prefix = substr $string, 0, shift @numbers, q();
    print $prefix . " " . $string;