http://www.perlmonks.org?node_id=1041255


in reply to Re: handling files using regular expression
in thread handling files using regular expression

yes, sorry.. i did forget to include that. but inspite of including the use strict and warnings, i did not get any warning and neither did my output file get updated. kindly help me.
#!/usr/bin/perl use strict; use warnings; my $input; my $start; open (FILE, 'name.tsv'); open (OFILE, '>probe_dist.tsv'); while (<FILE>){ ($input)= split ("\t"); $start= $input; } while (<FILE>) { $start =~ m/:(\d+)/; print OFILE "$start\n"; } close (FILE); exit;

Replies are listed 'Best First'.
Re^3: handling files using regular expression
by hdb (Monsignor) on Jun 28, 2013 at 13:54 UTC

    Just a few comments:

    • Your first while loop already runs through the whole file while not doing anything useful. Therefore the second while loop has nothing to do. Remove the first while loop altogether.
    • The statement while (<FILE>) of your second loop (now the only one...) will read a line at a time and assign it to $_. So you need to work with $_ within the loop block.
    • Your line $start =~ m/:(\d+)/; is applying the regex to the variable $start but you need to apply it to $_. Sou you might say $_ =~  m/:(\d+)/; which would work. It would be more Perlish to just say /:(\d+)/; as this would be applied to $_ by default.
    • The result of this match is that what was found in (...) is assigned to $1 so you need to write that to your file: print OFILE "$1\n";.
    This is probably not all but if you re-read the earlier thread you should find more best practices.

      Thank you so much. The code worked like a charm.
Re^3: handling files using regular expression
by marto (Cardinal) on Jun 28, 2013 at 13:57 UTC

    Firstly, when posting asking for help please post the actual code you're running. This code differs significantly from the code you have initially provided. Also, the advice in the post I linked to wasn't restricted to adding use strict; use warnings;, we also told you to use open properly, and to check for errors.

    Here you have two while loops for some reason, I've no idea why. Also you're splitting on tab but to one variable, and the input data you provide doesn't have any tabs at all.

    I'd suggest (again) that you take the time to learn the basics, and if you're going to ask for advice which you claim resolves your poroblem please either try and remember it or keep notes so that you use apply the same knowledge in future works.

Re^3: handling files using regular expression
by hippo (Bishop) on Jun 28, 2013 at 13:49 UTC
    while (<FILE>){ ... something ... } while (<FILE>) { ... something else ... }

    That second loop will never execute. Can you tell why?