
japhy
Enthusiast
Dec 22, 2000, 7:13 AM
Post #10 of 10
(582 views)
|
|
Re: Naming an array from a string?
[In reply to]
|
Can't Post
|
|
You suffer from "stringification", a common ailment resulting in the possibly dangerous (I kid you not) quoting of variables when they needn't or shouldn't be quoted. See my article for The Perl Journal for information on this affliction. I'd now like to comment on the code. The op() function has no need to send the name of a filehandle, does it? The filehandle gets used locally (and closed), so it doesn't need to be sent. And the reason you need to call eval() in that function is because doing <$foo> works, but doing <$foo{bar}> doesn't work. You could call the function readline(), instead, but I think you're going about this in a rather roundabout manner.
# $contents is a reference to an array # $contents->[0] is the first element, etc. $contents = op("setting.txt"); sub op { my $filename = shift; my @data; local *FH; chmod 0777, $filename; # WHY?! open FH, $filename; @data = <FH>; close FH; chmod 0000, $filename; # WHY?! return \@data; } I have to ask why you chmod() the file to 0777! This is quite unsafe, since this allows ANYONE to mess with the file in the small amount of time you give them. Perhaps the file should be kept at 0700 all the time, which allows only the owner of the program to access the file. Hmm, what else... oh, it is generally poor practice for a function to modify or create global variables. It's far better for the function to RETURN a value, which you then assign to a global variable. You see, it's very easy to accidentally overwrite a variable, if you just start using globals everywhere.
for ($i = 0; $i < 10; $i++) { print "$i = "; function($i); print "\n"; } sub function { my $x = shift; for ($i = $x; $i > 0; $i--) { print "$i, "; } print "\n"; } Do you see the problem? I use $i in the function, and since it's not localized, I've just screwed up the $i in the loop outside the function. So variables in functions should be declared with my, which makes them localized. Other miscellaneous (important) comments -- you should really endeavor to write your programs to work under the -w switch and the use strict pragma. -w will warn you of possible mistakes you've made, and use strict will probably seem like you're not allowed to do ANYTHING -- but it's there to make sure you're doing everything safely, like declaring ALL your variables (so that typos don't happen) and using hard references only, etc. Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author
|