On Fri, Apr 12, 2002 at 02:44:38AM -0400, Trey Harris wrote: > I think I've missed something, even after poring over the archives for > some hours looking for the answer. How does one write defaulting > subroutines a la builtins like print() and chomp()? Assume the code: > > for <> { > printRec; > } > printRec "Done!"; > > sub printRec { > chomp; > print ":$_:\n"; > } > > Assuming the input file "1\n2\n3\n", I want to end up with: > > :1: > :2: > :3: > :Done!: > > I assume I'm missing something in the "sub printRec {" line. But what? > (I also assume, perhaps incorrectly, that I won't have to resort to > anything so crass as checking whether my first parameter is defined...)
The first call to printRec, where you simply want to use the same $_ works without changes. Larry decided that ordinary subs don't topicalize, partly for this very reason. But you will be able to tell your subs to topicalize, using a property. It hasn't been decided yet if this property will be "is topic" or "is given", probably the latter. sub printRec ($msg is given) { ... } So for the second call to printRec, you could do something like: sub printRec ($msg //= $_ is given) { ... } Which would allow you to default to the outer $_ and make the first argument the topic. It's kind of ugly, though, and wouldn't deal with subsequent parameters in quite the way you would want. I much prefer handling the problem with overloading: sub printRec { chomp; print ":$_:\n"; } sub printRec ($msg is given) { printRec; } Allison