2014-07-20 117 views
1

我有一串數字和字符串文件,如下所示,我寫下了一個名爲字符串切割器的Perl代碼。我可以得到剪切的字符串,但我無法得到由數組排列的第一個「n」個字符串。任何想法?我不知道爲什麼substr不起作用。Perl切割字符串

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; 
} 

非常感謝

回答

3

的perldoc -f SUBSTR:

Extracts a substring out of EXPR and returns it 

所以,你應該做的是這樣的:

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