in reply to Re: Re: Re: where do you put your subs
in thread where do you put your subs
but I've also seen lots of good reasons why you'd want your subs at the bottom.1. It's easier to read. (IMHO)Really? But you dont list any.
To elaborate, I really like the allusion to programming to writing prose. Compare this:
with this...#!/usr/bin/perl; a_man_walks_into_a_bar(); man_says("Hello"); bartender_says("What'll ya have?"); man_says("Sasparilla. In a dirty glass"); exit; ### SUBS FOLLOW ### sub a_man_walks_into_a_bar { ... many lines of code } sub man_says { ... many lines of code } sub bartender_says { ... many more lines of code }
I don't know about you, but in the second example I'm NOT going to read the subs first... I'm going to scroll down (...down down down down) till I get to the good bits. Then I'm going to scroll back up (...up up up) to reference the subs. The subs don't have any context until I've seen the main logic, so I want the main logic (like the main story line) to be the first thing I see.#!/usr/bin/perl; sub a_man_walks_into_a_bar { ... many lines of code } sub man_says { ... many lines of code } sub bartender_says { ... many more lines of code } a_man_walks_into_a_bar; man_says("Hello"); bartender_says("What'll ya have?"); man_says("Sasparilla. In a dirty glass"); exit;
This gets worse when you wanna declare a global, which means you'd have to either:
...which in itself violates the "always put your variable declarations close to variable usage" rule, ormy $foo; ... zillions of lines of subs ... followed by your main logic
...which solves that problem, but might have other consequences.... zillions of lines of subs our $foo; or use vars qw($foo); ... followed by your main logic
BTW the code snippet you posted has a misnomer...Yeah, you're right. I don't write a lot of code that changes the package in the same file (I prefer separate files for separate packages) so file-scoped-lexicals-declared-at-the-top-of-a-file act virtually identically to package-globals-when-the-package-is-Main. My bad. :-D
I completely agree that newbie advice ought to be "best practices" but I'm not sure this is one of them, especially when there doesn't seem to be universal accord as to what's right. Even Merlyn puts his subs last in his Web Techniques columns, which are deliberately aimed at instructing others on how to do things the right way. If there's a "best practice" here I think it's "put all your subs together and all your logic together" to prevent some bozo from thinking
is a good idea. (Hey, there's probably someone out there like that. :-D)sub foo { ... } program logic sub bar { ... } more program logic
Gary Blackburn
Trained Killer
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Re: Re: Re: where do you put your subs
by Juerd (Abbot) on Mar 08, 2002 at 16:04 UTC | |
by Trimbach (Curate) on Mar 08, 2002 at 16:16 UTC |