Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Re: Improvement on script needed.

by Anonymous Monk
on Sep 08, 2003 at 17:06 UTC ( [id://289818]=note: print w/replies, xml ) Need Help??


in reply to Re: Improvement on script needed.
in thread Improvement on script needed.

Still cant get it to write to file:
my $db = 'C:\Inetpub\wwwroot\cgi-bin\test4.txt'; open(DATA, "$db") || die "Can not open: $!\n"; my @dat = (<DATA>); close(DATA); open(DATA, "$db") || die "NO GO: $!\n"; my %seen; while (<DATA>) { /^([^\|]+)\|(.*)/; # split at the first "|" my ($key, $value) = ($2,$1); next if $seen{$key}; print "$key: $value\n"; $seen{$key}++; push(@files,$key); pop @files; open(DATA,"> test4.txt") or die $!; print DATA @files; } close(DATA);

Replies are listed 'Best First'.
Re: Re: Re: Improvement on script needed.
by Not_a_Number (Prior) on Sep 08, 2003 at 20:08 UTC

    There are all sorts of problems with this code. You seem to have copied snippets from various answers to your question into your code without understanding any of them. I suggest you spend some considerable time studying the resources listed here.

    However, to return to your immediate problems, let's look, for example, at the number of times you use open in your code. Lines 3-7 are as follows:

    open(DATA, "$db") || die "Can not open: $!\n"; my @dat = (<DATA>); close(DATA); open(DATA, "$db") || die "NO GO: $!\n";

    Why on earth do you want reopen (for reading) the same file that you've just closed, once you've already read it into an array?

    As perl is forgiving, you can needlessly open (and/or close) the same file as many times as you want without it complaining, but...

    More importantly, the third time you use open is inside a while loop:

    while (<DATA>) { # ... open(DATA,"> test4.txt") or die $!;; # ... }

    Apart from the fact that - at least for clarity's sake - you shouldn't be using the same filehandle for two completely different files (and that in any case DATA is not a particularly good filehandle to choose...) - try to envision what the above is doing. As the open line is inside a loop, it will, for each iteration of the loop, open 'test4.txt' for overwriting. If you don't understand that, try running this:

    my $i = 0; while ($i < 5) { open (OUT, '>oops.txt') || die "NO GO: $!\n"; print OUT $i; $i++; }

    as compared with this:

    open (OUT, '>oops.txt') || die "NO GO: $!\n"; my $i = 0; while ($i < 5) { print OUT $i; $i++; }

    dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-19 04:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found