Mmmm, where to start?++ for using the strictures use strict; and use warnings;! You do know that you do not have to "pre-declare" the keys of your hash? my %info; is enough to make use strict; happy. It is considered beter to use as your filehandle a lexical variable, so open my $filehandle, ... would have given you extra points. And when your lexical variable goes out of scope, the file is closed automatically. The three argument version of open is again considered a better practice: open my $filehandle, '>>', 'C:\Documents and Settings\m\Desktop\info.t
+xt'
++ for checking the return value of the open. You do know that '>>' is opening the file in append mode, i.e. it retains it previous contents? That may be exactly what you want, so I am not criticizing this. Finally the loop can be re-written as follows (and it answers your third question): foreach my $key (qw/name Specialization age/){
print "enter your $key\n";
$info{$key} = <STDIN>;
chomp $info{$key}; # get rid of the EOL
print $filehandle "$key: $info{$key}\n";
}
Do not put single quotes around a variable ($info{$key} rater than $info{'$key'}) as it will be taken as a string literal and not as a variable.Unless you want to keep the EOL character at the end of each answer, use chomp to get rid of it. Finally, don't use <> unless you know what you are doing. The docs say as follows:
The null filehandle <> is special: it can be used to emulate the behavior of sed and awk. Input from <> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <> is evaluated, the @ARGV array is checked, and if it is empty, $ARGV[0] is set to "-", which when opened gives you standard input. The @ARGV array is then processed as a list of filenames. The loop
while (<>) {
... # code for each line
}
is equivalent to the following Perl-like pseudo code:
unshift(@ARGV, '-') unless @ARGV;
while ($ARGV = shift) {
open(ARGV, $ARGV);
while (<ARGV>) {
... # code for each line
}
}
except that it isn't so cumbersome to say, and will actually work. It really does shift the @ARGV array and put the current filename into the $ARGV variable. It also uses filehandle ARGV internally--<> is just a synonym for <ARGV>, which is magical. (The pseudo code above doesn't work because it treats <ARGV> as non-magical.) I bet you didn't know that!
CountZero A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James
|