This is a not terribly impressive and vaguely cute way to deal with the fact that $0 could be different lengths depending on how you call code (./foo, foo, /path/to/foo, etc...) I find it useful when writing usage statements that span multiple lines, allowing me to line up the code args properly underneath one another. It's kind of silly, but I need to start posting so I can start voting :)
sub usage { my $spaces = " " x ((length $0) + 7); print "Usage: $0 <some args....>\n"; print $spaces . "<some more args>\n"; exit; }

Replies are listed 'Best First'.
Re: formatting usage statements with $0
by naikonta (Curate) on Jul 06, 2007 at 08:32 UTC
    Why don't you strip $0 first to get only the basename? You may also want to fetch the current value of screen width, and recalcuate the length of all lines when printing the arguments downward, so they're all lined up nicely in the right (I'm not talking about right justify, just so your lines aren't broken unintendedly). May I suggest you to look at Text::Reform? Good luck with your effort to gain the voting power ;-)

    Update: (07-07-2007) I really meant "I'm not talking..." instead of "I'm talking..."


    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

      Stripping is a good idea. Thanks!

      Text::Reform isn't part of core in either 5.6 or 5.8 as far as I can see. It would reduce portability in my environment (many thousands of machines with different operating systems)

      I try to write only within core for the simple things. I see that Text::Reform would be handy for larger jobs though.

      Thanks for the advice! :)

Re: formatting usage statements with $0
by toolic (Bishop) on Jul 06, 2007 at 21:29 UTC
    In addition to stripping $0, you could also use a HERE document (see perlop) to get exactly the output you want. This is what I typically use:
    use File::Basename; my $prog = basename($0); sub print_usage { warn <<"EOF"; USAGE $prog [options] file DESCRIPTION Whatever this program should do. OPTIONS -h Print this help message -o dir Dump output file to specifed directory OPERANDS file A path name of an input file. FILES An output file is written to the current directory. The name of the file is foo. EXAMPLES $prog -o bar in.txt $prog -h EXIT STATUS 0 Successful completion >0 An error occurred EOF }