You're going to have to be more specific about how to tell the key from the value in your file? Are they just seperated by whitespace?Although his post was poorly formatted I think that they're separated by comma. But then there's no indication whatsoever whether there may be commas in the key and/or in the value respectively -suitably quoted, of course-, in which case Text::CSV_XS may be the best option.
Well, nothing to say about this, but the "open or die" idiom is so typically perlish that it seems strange to see anything different...unless ( open( FILE, "name_of_file" ) ) { die "Could not open file for reading\n"; }
As a possibly minor point, I always prefer the three args form of open and I prefer to use "lexical filehandles". I have to say that wrt this issue Abigail himself in clpmisc once supplied good arguments in favour of the two-args form. But as general rule my indications should be preferable in most situations, with modern enough perls.
Also, it is generally recommended, and is indeed sentible, to include $! in the error message.
You see, $_ is the "topicalizer". Its whole point (well, not the whole point, but a good portion of it) is that it is the implicit argument of many "actions". Sowhile (<FILE>) { if ($_ =~ /^(maintenance_mode)\s([\w,=]*)$/) {
is OK, but$var =~ /whatever/;
is plainly equivalent to$_ =~ /whatever/;
with the only difference that the latter is clearer. Well, to a perl programmer, of course! Occasionally people even uses a for for its aliasing properties only, e.g.:/whatever/;
BTW: your regexp will only match one key, so that I wouldn't regard it as especially useful for filling a hash;for ($foo) { s/^"//; s/"$//; s/\W+/-/; } # or also: # s/^"//, s/"$//, s/\W+/-/ for $foo;
$hash{$1} = $2; } }
Also, what you did is certainly legitimate, but since here we're talking about breaking a string in two parts, perhaps split could have been better suited for the job. This, of course, modulo the caveat I already took care of above. En passant it occurs to me that it may be worth to remind you of the LIMIT parameter of split, that is not that known after all...
PS: for such minimal examples (and for much more) IMHO the ARGV filehandle is invaluable. See also the discussion going on at How would you do it? Re ARGV, fundamentally!, and especially merlyn's answer
In reply to Re^2: create a hash by reading file
by blazar
in thread create a hash by reading file
by s_gaurav1091
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |