CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Could you check this script? Keeps churning out files that are 0kb

 



effc
Novice

Nov 1, 2012, 5:39 AM

Post #1 of 4 (1076 views)
Could you check this script? Keeps churning out files that are 0kb Can't Post

Hi I'm searching through a directory of files that are about 700kb a piece for the string ^ASSAY=BLAH_BLAH_BLAH, I need to replace the BLAH_BLAH_BLAH with CHA21 (and add.manual, which is working properly). The files that I come up with are 0kb.



#!/usr/bin/perl

opendir(FILES, ".") || die; #open current directory

foreach (readdir(FILES))

{

{

$next_file = $_;

chomp($next_file);

print "$nextfile.$suffix\n";

if ($next_file =~ m/.sift/)

{

open (IN, "<$next_file" || die);

print "$next_file\t";

$next_file=~ s/\.sift//;

print "$next_file.manual.sift\n";

open (OUT, ">$next_file.manual.sift" || die);

while ($line = <IN>)

{

if($line =~ /^ASSAY=BLAH_BLAH_BLAH/){

$line =~ s/BLAH_BLAH_BLAH/CHA21/gi;

}

}

}

close OUT;

close IN;

} # close OUT;

# close IN;

}

Thanks in advance!


BillKSmith
Veteran

Nov 1, 2012, 7:07 AM

Post #2 of 4 (1073 views)
Re: [effc] Could you check this script? Keeps churning out files that are 0kb [In reply to] Can't Post

You must print every line (whether you changed it or not) to the OUT file.

Code
        while ( $line = <IN> ) { 
if ( $line =~ /^ASSAY=BLAH_BLAH_BLAH/ ) {
$line =~ s/BLAH_BLAH_BLAH/CHA21/gi;
}
print OUT $line;
}


I recommend several other improvements.

always use

Code
use strict; 
use warnings;

Fix all the errors that they reveal.

The variable $suffix does not do anything useful and should be removed completely.

Use the three argument form of open. (refer: perldoc -f open)

Use lexical filehandles.

Your test for the success of open is an excelent practice. You should supply a message with die to tell the user what happened.

You may not want the program to abort because one open fails. Consider the block form of eval to trap the error. (Refer: perldoc -f eval)

Close the directory at the end of your program.
Good Luck,
Bill


effc
Novice

Nov 1, 2012, 7:38 AM

Post #3 of 4 (1070 views)
Re: [BillKSmith] Could you check this script? Keeps churning out files that are 0kb [In reply to] Can't Post

Thank you so much that was incredibly helpful! Perl script ran perfectly.


Laurent_R
Veteran / Moderator

Nov 1, 2012, 8:24 AM

Post #4 of 4 (1068 views)
Re: [effc] Could you check this script? Keeps churning out files that are 0kb [In reply to] Can't Post

You could simplify your check and avoid using two regexes:


Code
       while ( $line = <IN> ) {  
$line =~ s/^ASSAY=BLAH_BLAH_BLAH/ASSAY=CHA21/i) ;
print OUT $line;
}


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives