Come for the quick hacks, stay for the epiphanies. | |
PerlMonks |
A vexing list vs. scalar context question.by theguvnor (Chaplain) |
on Jan 31, 2002 at 23:47 UTC ( [id://142547]=perlquestion: print w/replies, xml ) | Need Help?? |
theguvnor has asked for the wisdom of the Perl Monks concerning the following question:
In my latest folly, I changed an object to use several accessor methods that would return a scalar, rather than one accessor that would return a hash ref (that had to be dereferenced and I figured was an extra hassle for any script using the module). So, rather than getting a value like my $dir = $site->dirs()->{'uploads'};, I could write my $dir = $site->upload_dir; All well and good, except my object also has a couple of accessor methods that should return arrays rather than scalars, so my return from the accessor method looks like:
It must be noted I'm using closures in a loop to create the accessor methods, hence the conditional return. See my accessor generator at the bottom. End of preamble - this is where I got tripped up and nearly went insane - in my calling script, I wanted to join the return from the 'upload_dir' method to something else, like so: my $dir = join '/', $site->upload_dir, $user->id; Now, it should be obvious given my preamble that because I have called the upload_dir method in list context (because join expects a list) my method will return (or try to return) a "listified" version of my scalar upload_dir value, and hence won't be what I'm looking for - in this case, it ended up returning an empty list, and messing everything up.But it took me over an hour to figure this out (I'm not too bright at times :). What I can't figure out is why use strict; and use warnings; didn't throw me some kind of message about trying to turn my scalar (upload_dir) into an array to return from the method?
Back to
Seekers of Perl Wisdom
|
|