vikuuu has asked for the wisdom of the Perl Monks concerning the following question:

I am a new learner of the perl. I have a file which contains this pattern DP - 2010 Dec; PG - 551-555 ; AD - Direccion General de Epidemiologia, Ministerio de Salud del PeruPerú AU - Nunura R J; DP -.. PG -... Again the pattern goes the same I want to print whatever written after AD and want to save the output in another file.Please help in this regard

Replies are listed 'Best First'.
Re: String related question
by Utilitarian (Vicar) on Feb 02, 2011 at 11:04 UTC
    We are not a code writing service, however we are very willing to help you learn. Try coding up the following and come back to us with specific issues you are having.
    • open the input file for reading
    • open a file for output
    • while there are entries in the file
      • if the line begins with 'AD'
        • print the line to the output file
    • close both files
    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
      I have written this code but it is wrong please help me in correcting this
      $proteinfilename=<STDIN>; chomp $proteinfilename; open(FILENAME,$proteinfilename); @array=<FILENAME>; if ( @array=~m (/^AD/)){ print " @array"; }
        That is a reasonable attempt.

        Your error is that you're trying to apply the match to the whole array of lines at once, instead of to each line individually. Try this as a correction to your code:

        foreach my $line (@array) { if($line =~/^AD/){ print " $line"; } }

        For tasks like you've described, there's no reason to read the entire file into an array. It's usually better to process the file line by line, because it scales in case your files should get huge. I.e. for, say, a 1 GB file, you'd need several gigs of RAM to hold the contents in the array, while if you process line by line, you'll only ever need storage for one line.

        open my $fh_in, "<", $proteinfilename or die "Couldn't open '$protein +filename': $!"; open my $fh_out, ">", $outfilename or die "Couldn't open '$outfilename +': $!"; while (my $line = <$fh_in>) { if ($line =~ /^AD/) { print $fh_out " $line"; } }
Re: String related question
by moritz (Cardinal) on Feb 02, 2011 at 11:05 UTC

    Open the output file.

    Read the file one line at a time. For each line, extract the wanted information, and print it to the output file.

    Close the output file.

    perlintro and perlretut should give you enough information to get started, and maybe even complete your task. Feel free to ask more specific questions once you run into problems. Make sure to include the code you wrote, and the specifics of your problems with it.