in reply to Re: Modular Code
in thread Modular Code

Well...

open_file is not really just opening the file, it is grabbing the contents of the file; You might want to make the name of the sub match the action of the sub more closely.

I would not declare the my @contents outside the sub and then rely on the side effect of the sub altering the data in contents. Instead I would pass the @contents into the sub by reference, and have it filled that way. This avoids creating two different arrays and copying them around via pass-by-value.
Side effects can be confusing when code gets reused later. For instance this code snippet is only useful if you want to fill a previously existing array named contents -- not very modular.

It also might be useful for the calling routine to be able to tell if an error occurred during the "grabbing"; Passing back an error code would allow the caller to gracefully recover from any possible error. I believe it is better to allow the caller to recover from the error rather than the "grabber" because any number of callers may want to react in a different way, so returning the code allows that -- reacting with the die inside the "grabber" does not. Returning a '0' can signify no error occured.

my @contents; my $error = grabFile('myfile.txt', \@contents); sub grabFile { open(FILE, $_[0]) || return ($!); @{$_[1]} = <FILE>; close(FILE); return 0; }

And this is not OOP.... OOP is much more than this.

Replies are listed 'Best First'.
Re: Re: Re: Modular Code
by Stamp_Guy (Monk) on Jun 14, 2001 at 23:07 UTC
    This is EXACTLY what I wanted to do. I didn't know you could do certain things like @{$_[1]} though. That will come in quite handy as I learn more about this. Got any suggestions where I could learn more about this type of coding?
      There is a small module called File::Slurp that you may want to look at.