Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: help manipulating data in an array.

by TedPride (Priest)
on Nov 12, 2004 at 07:39 UTC ( [id://407289]=note: print w/replies, xml ) Need Help??


in reply to help manipulating data in an array.

The simplest way to do this is as follows:
use strict; use warnings; my (@numbers, $handle); open ($handle, "c:/documents and Settings/david price/my documents/cin +gular.txt") || die "cannot open: $!"; @numbers = <$handle>; close ($handle); for (@numbers) { if (index($_, '9432') != -1) { print "match found\n"; } else { print "match failed\n"; } }
Use strict and use warnings will tell you if you do naughty things with your code, like forgetting to set scope on your variables (my means scope is inside the current block). Using (locally scoped) variables for your handles rather than names means your handle can't conflict with other handles; using a for loop on your lines means you don't have to mess with line numbers; using substr means your matching is much more efficient than if you used regular expressions.

Line by line analysis of your code is as follows:

open (CINGULAR, "c:/documents and Settings/david price/my documents/ci +ngular.txt") || die "cannot open: $!"; # USE VARIABLES FOR FILE HANDLES INSTEAD OF NAMED FILE HANDLES @number=<CINGULAR>; # DECLARE A SCOPE FOR ALL VARIABLES. my @number=<CINGULAR>; would be b +etter close (CINGULAR); $count=0; # SAME while ($count<100) { # IF YOU WANT TO LOOP THROUGH AN ARRAY, USE SOMETHING LIKE: # for (my $c = 0; $c <= $#number; $c++) { print $number[$c]; } # for (0..$#number) { print $number[$_]; } # for (@number) { print $_; } # foreach (@number) { print $_; } # $#number is the address of the last item in the array. # $_ is the default input / output variable. if (@number=~[/^9432$/g]) { # PROPER SYNTAX IS if ($number[$count] =~ /9432$/) { # The g flag is used for multiple matches; ^ and $ are only used toget +her # if you want a match at both ends - in other words, an exact match. # I don't know what the brackets were for. print "match found"; } else { print "match failed"; } $count++; # THIS IS FINE. HOWEVER, YOU COULD HAVE SAVED A STATEMENT BY DOING: # while ($count++ < 100) { }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-04-19 11:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found