0

I have a file that looks like this:

A:B:C
G:P:T
K:M:Q
...

I have loaded the file in an array @letters.

I need to retrieve each letter without the : and pass it as a parameter to another script that I call.

so

/bin/kish -x /home/whatever/testscript $letter[0 1] $letter[0 2] $letter[0 3]

then

/bin/kish -x /home/whatever/testscript $letter[1 1] $letter[1 2] $letter[1 3]

until end of array.

Any suggestions?

2
  • tried split(":")? perldoc Commented Jun 28, 2013 at 2:33
  • Don't fool yourself into thinking the first arg of split is a string. Use split /:/ Commented Jun 28, 2013 at 4:37

2 Answers 2

1

So first we need to build a multidimensional array, the best way I know to do this in Perl is using references:

use strict;
use warnings;

open( my $fh, "<", "data" );
my @rows;
while ( my $line = <$fh> ) {
    chomp $line;
    my @row = split(':', $line) ;
    push( @rows, \@row );
};

The \ operator in \@row means that each element of the list @rows is actually a reference to another list @row. This allows for the sort of nested indexing which you seem to be seeking, like so:

`/bin/kish -x /home/whatever/testscript $rows[0]->[0] $rows[0]->[1] $rows[0]->[2]`

First we index into the list as usual (this is the "row" number). The arrow operator -> dereferences the reference to the list, then we index into that dereferenced list with the appropriate "column" number

Sign up to request clarification or add additional context in comments.

3 Comments

Loading the array worked well, thanks! I can print each element using:
Loading the array worked well, thanks! I can print each element using: foreach my $index (0..$#rows) { print "$rows[$index]->[0]\n"; print "$rows[$index]->[1]\n"; print "$rows[$index]->[2]\n"; but when I substituted the prints with exec (" /bin/ksh -x /home/blah/test1 $rows[$index]->[0] $rows[$index]->[1] $rows[$index]->[2]"); } it only executes the script for the 1st element and not the other. Any ideas. thanks!
you should use system and not exec
0
while ($line=<FILEHANDLE>) {
    @letters=split(/\W+/,$line);
    system("/bin/kish -x /home/whatever/testscript $letters[0] $letters[1] $letters[2]");
}

You will need to open FILEHANDLE first. The while() loop (first) reads the file, one line at a time. The second takes the line, breaks it into chunks (non-alphanumeric characters [such as ":"] are used to define the breaks between the chunks). The system line runs the command itself. The last line "}" shows where the loop ends.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.