# ------------------------------------------------- # Read an array from a file # ------------------------------------------------- # ask user for filename print "filename? "; my $file = <>; chomp $file; # ask user for number of rows print "How many rows in your file? "; my $rows = <>; chomp $rows; # ask user for number of columns print "How many columns in your file? "; my $cols = <>; chomp $cols; # read my file my $2d = readdt2($file,$rows,$cols); # print output use Data::Dumper; print Dumper $2d; # just want to now what the 5th row, 3rd column is print $2d->[4][2],"\n"; # ------------------------------------------------- # subroutine to read a generic 2d array from a file # ------------------------------------------------- sub readdt2 { # get the name of the file to read my $ifn = shift; # get the number of rows of the array you want to read my $I = shift; # get the number of columns you want to read my $J = shift; # open the file (note that it is commented out for now for testing) # open(my $IFH, "<$ifn") or die "cannot open file $ifn\n"; my @ret; # read $I number of lines from your file (0 to $I-1) foreach my $i (0 .. $I-1) { # read one line from your file # (for testing purpose, read data following the __DATA__ statement below) my $line = ; # take your line from your data file, and split into an array, using spaces as your deliminator my @tmp = split(/\s+/,$line); # take the first $J columns from your array, my @columns = @tmp[ 0 .. $J-1 ]; # and make your i(th) row point to your array of columns $ret[$i] = \@columns; } # return your array of arrays (i.e. a 2-d array) return(\@ret); } __DATA__ 11 12 13 14 15 16 17 21 22 23 24 25 26 27 31 32 33 34 35 36 37 41 42 43 44 45 46 47 51 52 53 54 55 56 57 61 62 63 64 65 66 67