【问题标题】:Perl cutting stringPerl 切割字符串
【发布时间】:2014-09-10 23:16:33
【问题描述】:

我有一个数字数组和字符串文件,如下所示,我写下了一个名为字符串切割器的 perl 代码。我可以得到切割的字符串,但我不能得到由数字数组分配的第一个“n”字符串。任何想法?我不知道为什么 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;
}

非常感谢

【问题讨论】:

    标签: string perl substring substr


    【解决方案1】:

    perldoc -f substr:

    Extracts a substring out of EXPR and returns it
    

    所以你应该这样做:

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

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      相关资源
      最近更新 更多