Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^2: Need Help in Array

by GrandFather (Saint)
on Jan 03, 2012 at 23:36 UTC ( [id://946160]=note: print w/replies, xml ) Need Help??


in reply to Re: Need Help in Array
in thread Need Help in Array

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://946160]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-24 10:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found