in reply to Need Help in Array

#! /usr/bin/perl open(FILE,"<file.txt"); my @lines=<FILE>; close(FILE); my $module; my $id; foreach my $line(@lines) { chomp($line); if($line=~ /Module.*/) { $line=~ /:\s*/;$module=$'; } if($line=~ /ID.*/) { $line=~ /:\s*/;$id=$'; } if($line=~ /Customer : yes/i) { print "$module and $id\n"; } }
outputs (with your data)
1 and 001 3 and 003

Replies are listed 'Best First'.
Re^2: Need Help in Array
by GrandFather (Saint) on Jan 03, 2012 at 23:36 UTC

    Your sample would be better written:

    #!/usr/bin/perl use warnings; use strict; my $dataStr = <<DATA; Module: 1 ID:001 Customer : yes Module: 2 ID:002 Customer : no Module: 3 ID:003 Customer : yes Module: 4 ID:004 Customer : no DATA my $filename = 'file.txt'; #open my $inFile, '<', $filename or die "Unable to open $filename: $!\ +n"; open my $inFile, '<', \$dataStr; my $module; my $id; while (defined (my $line = <$inFile>)) { chomp ($line); if ($line =~ /Module:\s*(\S+)/) { $module = $1; next; } if ($line =~ /ID:\s*(\S+)/) { $line =~ /:\s*/; $id = $'; next; } if ($line =~ /Customer : (\w+)/i) { print "$module and $id\n" if $1 eq 'yes'; $module = '-- missing module --'; $id = '-- missing ID --'; } }

    which uses three parameter open, lexical file handles, sample data included in the code, checked open result (in the commented "real" open), explicit use of strictures, while loop rather than file slurp and for loop, and improved handling of badly formed data.

    True laziness is hard work