Svetlana Gelpi Svetlana Gelpi - 1 year ago 76
Perl Question

How do I specify these variables correctly on perl?

I ran a molecular dynamics simulations which gave me 2,000 trajectory files. These files have the file name format

up to 2000. I wrote a general perl program but it isn't reading through the 2,000 files. How do I modify my code so it reads every file and extracts the coordinates I want for each file individually? I need 2,000
files. The tinker file here is the
file. Here is the code I wrote:

#!/usr/bin/env perl
use Math::VectorReal;
use Math::Trig qw/acos/;
use strict;
use warnings;

my $file1 = $ARGV[0];
my $n1 = $ARGV[1];
my $n2 = $ARGV[2];
my $tinker_file = sprintf "%s.%03d"

my( $file1, $n1, $n2 ) = @ARGV;

foreach $tinker_file (glob "$tinker_file.*") {
print "Filename: $tinker_file\n";

my $file2 = "coordinates_of_interest.dat";
my %lines_of_interest = map { $_ => 1 } 18, 25, 26;

open(FILE2, '>', $file2) or die "couldn't open the file!";

for(my $i=$n1;$i<=$n2;$i++){
open(FILE1, '<', $tinker_file) or die "couldn't open the file!";

my $num_lines = keys %lines_of_interest;

while (<FILE1>) {
if ($lines_of_interest{$.}) {
print FILE2;
last unless --$num_lines;




Answer Source

glob is your friend here either use it with a wildcard and search the directory:

my ( $filespec, $n1, $n2 ) = @ARGV; 

foreach my $file ( glob "$filespec.*" ) { 
   print "Filename: $file\n";

Or you can use glob to expand a pattern:

my $expr = join ",", 0..9;

foreach my $entry ( glob ( "test.{$expr}{$expr}{$expr}" ) ) {
   print $entry,"\n";

But I'd probably stick with the first one, as that'll make sure files actually exist.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download