in reply to File Parsing

This should work:
#!/usr/bin/perl use strict; use warnings; BJSFM_MS(); sub BJSFM_MS { my @temp; my $string1="FAILURE CRITERIA PER PLY"; my $string2="AUTOMATIC SEARCH FOR FAILURE"; while (my $line = <DATA>) { if ($line =~ /$string1/) { undef @temp; <DATA> for 1 .. 3; while (my $inner = <DATA>) { last if $inner =~ /^$/; push @temp, $inner; } } } use Data::Dumper; print Dumper \@temp; } __DATA__ FAILURE CRITERIA PER PLY DIST ANGLE PLY FAILURE NUMBERS 1 2 SHEAR 0.000 0.00 -45.00 0.238 0.282 -1.459 0.000 0.00 0.00 0.971 1.369 0.004 0.000 5.00 -45.00 0.475 0.142 -1.585 0.000 5.00 0.00 1.003 1.531 -0.274 0.000 10.00 -45.00 0.721 0.037 -1.623 FAILURE CRITERIA PER PLY DIST ANGLE PLY FAILURE NUMBERS 1 2 SHEAR 0.000 0.00 -45.00 0.247 0.293 -1.514 0.000 0.00 0.00 1.008 1.422 0.004 0.000 5.00 -45.00 0.493 0.147 -1.645 0.000 5.00 0.00 1.042 1.589 -0.284
You declare variables in a wider scope than needed. If you do not need the skipped lines, there is no reason to keep them in variables. Also, I do not see any benefit in using a hash if its keys are integers in the sequence 1, 2, 3, ...; I used an array instead. In your original do { ... } until, you would have needed something like until eof or $temp{$n-1} =~ /^$/.

Replies are listed 'Best First'.
Re^2: File Parsing
by shortyfw06 (Beadle) on Jun 14, 2012 at 14:51 UTC

    The example in the original post is one step in my overall goal. In moving forward, I think I do want a hash, however, the hash value for key 1 should be @array. Then the @array is undefined and the next match creates a new @array with is then the hash value for key 2. This process is repeated until all matches have been found in the file for each element in @headers. I am really struggling with this one.... I hope my explanation is clear. Here is my attempt at this.

    #!usr/bin/perl use Tk; use Cwd; use strict; use warnings; # ###################################################################### +##################### # GUI Building ###################################################################### +##################### # # Create Main Window my $mw=new MainWindow; my $filename; my $line; my $n; my @headers = ("LAMINATE PROPERTIES", "LAMINATE STRESSES", "LAMINATE STRAINS", "CIRCUMFERENTIAL AND RADIAL STRESSES & STRAINS", "DISPLACEMENTS", "STRAINS PER PLY", "STRESSES PER PLY", "FAILURE CRITERIA PER PLY"); my $inner; my @array; my %hash; my $ms_button = $mw->Button(-text=>"MS", -command=> \&BJSFM_MS)->pack(); MainLoop; sub BJSFM_MS { $filename="BJSFM_out.prn"; open(OUTPUT_FILE, "< $filename") or die "Can't find $filename!"; $n=1; while ($line = <OUTPUT_FILE>) { if ($line =~ /$headers[$n-1]/) { undef @array; #This clears the previous two instances + of $string1 <OUTPUT_FILE> for 1..3; while ($inner = <OUTPUT_FILE>) { last if $inner =~ /^$/; push @array,$inner; } $hash{$n}=@array; $n++; } } close OUTPUT_FILE; print @array; print %hash; }