B. Fongo wrote: > Hi > > I have a file containing arrays of numbers. I 'm trying to get a > subroutine iterate the file and print ONLY arrays with three elements > into a second file. None of the elements has more than 2 digits. So I > tried with a pattern match, it fails to deliver the right result. > > I want it to find and print array with 3 elements like: > > 1 2 5 > 20 33 45 > 5 17 25 > > > > sub get_arr{ > > open (OUTPUT, "permed.dat") || die "Could not open file. $! \n"; > open (INPUT, ">cleaned_up.dat") || die "Could not open file. $! > \n"; > > my ($clean, @clean, $cleanprint, $arrlength, $result); > $clean = <OUTPUT>; > while ( $clean ){ > > @clean = split (" ", $clean); > print INPUT ("@clean") if (@clean =~ > /\d+\s+\d+\s+\d+/); > $clean = <OUTPUT>; > > } > > die ("Could not close output file. $! \n") unless close > (OUTPUT); > die ("Could not close input file. $! \n") unless close (INPUT); > }
I weary of this incantation: use strict; # always use warnings; # usually If these had been in place you would have got a nice informative warning Applying pattern match (m//) to @array will act on scalar(@array) In other words you are applying a pattern match to the string '3' (or however many elements are in the array). Since this will never contain any whitespace the regex will never match and your output will contain nothing. Here's a solution which will work for you. It splits each line into the @clean array and checks, firstly that @clean contains three elements, and secondly that no elements contain non-numeric characters. All rows passing both tests are output. use strict; use warnings; open OUTPUT, 'permed.dat' or die $!; open INPUT, '> cleaned_up.dat' or die $!; while (<OUTPUT>) { my @clean = split; next unless @clean == 3; next if grep /\D/, @clean; print INPUT "@clean\n"; } close OUTPUT or die $!; close INPUT or die $!; HTH, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]