Computing.Net > Forums > Programming > perl program

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

perl program

Reply to Message Icon

Name: rayken1
Date: June 23, 2009 at 22:51:09 Pacific
OS: Macintosh
Subcategory: General
Comment:

open(FILE, "<", "numb.txt" ) || die "Unable to open numb.txt <$!>\n";

while ( <FILE> ) {
chomp;
$fileHash{$_} = $i++;
}

close(FILE);

open(FILE, "<", "num.txt" ) || die "Unable to open num.txt<$!>\n";

while( <FILE> ) {
chomp;
if( exists $fileHash{$_} ) {
}
else {
print "$_\n";
}
}

close(FILE);

Kindly help me with this code so that I can append or write (output) the string that is selected onto the second file.

Thanks.



Sponsored Link
Ads by Google

Response Number 1
Name: David Perry
Date: June 24, 2009 at 04:21:18 Pacific
Reply:

You have opened the second file for read. You need to open for read / write.

http://www.perlfect.com/articles/pe...

You should name to two file handles differently to avoid confusion.

To append to a file you have open for write, you can do something like

open FILE, ">filename.txt" or die $!;
print FILE "String" ;
close FILE;


0

Response Number 2
Name: FishMonger
Date: June 24, 2009 at 06:12:44 Pacific
Reply:

To append to an existing file you need to open it in append mode, which is '>>'. If you use '>', that will overwrite the file, which means you'll loos any data that was already in the file.

Here's some comments on the code.

You're using the 3 arg form of open, which is good, but you should also be using a lexical var for the filehandle instead of the bareword and my personal preference is to use the lower precedence or instead of ||.

open my $FILE, '>>', 'num.txt' or die "Unable to open num.txt <$!>\n";

Having an if block that does nothing is pointless. Just reverse the logic and print.

while( <$FILE> ) {
    chomp;
    print "$_\n" if not exists $fileHash{$_};
}


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: perl program

Simple perl program www.computing.net/answers/programming/simple-perl-program/5985.html

Need Perl Programming Help!!!!! www.computing.net/answers/programming/need-perl-programming-help/762.html

Basic PERL programming script www.computing.net/answers/programming/basic-perl-programming-script/16791.html