Karyo
Karyo

Reputation: 372

Perl cutting string

I have an array of numbers and file of strings looks like the below and I have written down a perl code which named string cutter. I can get the cut strings, but I can't get the frist "n" strings assgined by the array of numbers. Anyidea? I do not know why substr does not work.

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

My code:

#!/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;
}

Many thanks

Upvotes: 1

Views: 345

Answers (1)

Lajos Veres
Lajos Veres

Reputation: 13725

perldoc -f substr:

Extracts a substring out of EXPR and returns it

So you should do this way:

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

Upvotes: 3

Related Questions