Melly has asked for the wisdom of the Perl Monks concerning the following question:

I've been happily using Getopt for sometime, but it only recently crossed my mind to wonder what the hell is going on when options are assigned to variables.

GetOptions( "header=s" => \$default_header )

Basically, what's going on with "header=s" => \$"? If I wasn't familiar with Getopt, I'd be scratching my head over why I'm passing a weird string ("header=s") and a reference to $default_header to a function called GetOptions, and using a hash assignment to do it.

map{$a=1-$_/10;map{$d=$a;$e=$b=$_/20-2;map{($d,$e)=(2*$d*$e+$a,$e**2 -$d**2+$b);$c=$d**2+$e**2>4?$d=8:_}1..50;print$c}0..59;print$/}0..20
Tom Melly, pm (at) cursingmaggot (stop) co (stop) uk

Replies are listed 'Best First'.
Re: Getopt::Long - why \$ ?
by Corion (Patriarch) on Oct 29, 2018 at 14:25 UTC

    How would you define an interface where you specify a string and a place where to store the value if that string is matched somewhere?

    You pass a list of pairs to GetOptions(...), and that list of pairs is 1) the specification of the switch ("name|alias=value type") and 2) the place where the value should be written to. The way to pass a place around in Perl is usually to pass a reference to the target around, which is what happens with the \$foo thing.

    An alternative approach is to make GetOptions(...) store all things it finds in a hash. This will give you a plain hash without weird syntax, but on the downside, you lose the typo checking that strict.pm provides.

      Ah, got it. I think my conceptual problem was that I don't think I ever use (or think of) references as a way to set the referenced variable's value. A reference to me tends to mean that either I need a complex data-structure, or I've got a fussy return from a subroutine (e.g. two separate variable-length lists that I need to keep separate).

      Anyway, many thanks your holiness.

      map{$a=1-$_/10;map{$d=$a;$e=$b=$_/20-2;map{($d,$e)=(2*$d*$e+$a,$e**2 -$d**2+$b);$c=$d**2+$e**2>4?$d=8:_}1..50;print$c}0..59;print$/}0..20
      Tom Melly, pm (at) cursingmaggot (stop) co (stop) uk
Re: Getopt::Long - why \$ ?
by ikegami (Patriarch) on Oct 30, 2018 at 02:21 UTC

    There's no hash in there. "=>" is just a fancy way of writing ",", and it has nothing to do with hashes. (An identifier on the LHS of => is also treated a string literal, but that's not relevant here.)