Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: For loop problem

by ehdonhon (Curate)
on Nov 28, 2002 at 14:56 UTC ( #216313=note: print w/replies, xml ) Need Help??

in reply to For loop problem

for ($d=1;$d<10;$d++){
That's going to iterate $d from 1 to 9. Its valid syntax, but its easier to read, and more perlish this way:
for my $d ( 1..9 ) {

if ($line =~ /^(\d{1,10})/){
This is going to evaluate to true if $line contains a string of numbers. It will assign up to the first 10 consequitive numbers into $1.

if ($d =~ /^$key$/){
This is going to evaluate true if the string of numbers is contained within $d. In other words, this is going to evaluate to true if the very first string of numbers that you found in $line was a single digit between 0 and 9. So, any of the following lines are guaranteed to never match:

this is my 023 string
hello 10
hi there 0
how are you 03

Replies are listed 'Best First'.
Re: Re: For loop problem
by matth (Monk) on Nov 29, 2002 at 10:35 UTC
    Thanks for your advice which has raised a point and a question in my mind. Point: The tags are on the inner most left side of the text file. I need $d and $key to be an exact numeric match. Question: Does the if ($d =~ /^$key$/){ not cover this in every circumstance? Point: I tried to do a numeric match but the $key is treated as a string.
      Something like this would probably make more sense (if I understand your situation correctly):
      open( OUTPUT_XML_A_OPEN, $output_XML_A_open ); open( NEW_OUTPUT_XML_A, "+>>", $new_output_xml_a ); for $d ( 1..9 ) { seek( OUTPUT_XML_A_OPEN, 0, 0 ); while (<OUTPUT_XML_A_OPEN>) { chomp; # I'm leaving out a lot of your debugging stuff if( /^$d\D/ ) { # does this line start with "$d"? print NEW_OUTPUT_XML_A; } } }

      As I understand it, you are trying to find lines in the input file that begin with single-digit numbers, and print these to an output file in sorted order (all the "1" lines first, then all the "2" lines, etc), without worrying about any sub-sort ordering (all the "1" lines can be in any order).

      In that regard, I wonder why you open the output file for "append" access (">>") -- and why you open it for both read and write access (using "+"), when you don't really need to read it here?

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2022-05-18 13:01 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (70 votes). Check out past polls.