in reply to While loop not printing anything after using grep
I would open your input file, read it into a hash. Make sure that Friday is in the hash (whether it was in the input file or not). Sort the hash according the European sort order and print to a file. The safest way to do this is to output to a temp file. Then delete original file. Then rename temp file to the original file name. The purpose of that is to make sure that the data is not "lost" if program crashes while updating its input file.
Below, I use the already opened DATA file handle and just print to stdout. I think you know how to open files for reading or writing - so I leave that part to you. The code does do some "unnecessary" work if Friday is already there. But the flow is simple with no "if" statements.
Update: I guess if you want to know if Friday was there or not? The ternary op is good for that, but longer winded code is just fine and will execute just as fast.use strict; use warnings; my %day_of_week_order = ( Monday =>1, Tuesday => 2, Wednesday =>3, Thursday => 4, Friday => 5, Saturday => 6, Sunday => 7); my %days = map{chomp; $_=>1}<DATA>; $days{Friday} = 1; # make sure Friday is there foreach my $day (sort{my $A = $day_of_week_order{$a}; my $B = $day_of_week_order{$b}; $A <=> $B } keys %days) { print "$day\n"; } =prints Monday Friday Saturday Sunday =cut __DATA__ Monday Saturday Sunday
Also, you should be aware that file operations are "expensive" both for CPU and execution time wise. It is rare to seek to the beginning of a file and re-read it because reading the file from disk is so "expensive". A seek() will flush all buffers and you are basically starting from scratch again (Data has to be re-read from disk). For a small file, read it into memory - do necessary edits and then write it back out. "Small" is a relative term, but your file certainly qualifies!exists ($days{Friday}) ? print "Friday was there\n" : print "Friday wasn't there\n";
Another Update: The general approach of your code is seriously flawed in terms of extensibility (make "Friday" the second line if its not already the second line). What happens if the input file has "Tuesday" as the second line? Then Friday needs to go on the 3rd line! The above code would do that.
|
|---|