[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Command-line mystery



The following code was causing regex on DALnet #perl much chagrin:

  $x = { 'a' => \&foo };
  sub foo { print 'bar' }
  $x->{a}->();

For some reason, it did not print for him, yet if he replaced 'bar' with
"bar", it printed.  It turns out he was doing this at the command-line:

  perl -e '$x={'a'=>\&foo};sub foo{print 'bar'};$x->{a}->()'

First I said "silly you, you're using ' as your -e quote character".

Then I said "why the hell isn't the shell bitching at you?"

Then I ran it through -MO=Deparse, and was shocked when I saw that Perl
got the ENTIRE code.  But then I noticed that it was doing

  sub foo {
    print bar $_;
  }

Guh, I said.  Then I realized that the -e gets a single argument, and all
whitespace must be contained within quotes.  The much simpler case is:

  perl -e 'print 'foo''

This is really

  perl -e 'print foo'

since the -e option receives as its argument a quoted string and an
unquoted string and another quoted string; "print ", foo, and "".  If you
make a tiny adjustment:

  perl -e 'print 'foo' . 'bar''

then it prints foobar, but only because Perl sees

  perl -e 'print foo . bar'

Of course, had -w been used, bareword warnings (or use of
uninit. values) would have been elicited.

-- 
Jeff "japhy" Pinyan     japhy@pobox.com     http://www.pobox.com/~japhy/
PerlMonth - An Online Perl Magazine            http://www.perlmonth.com/
The Perl Archive - Articles, Forums, etc.    http://www.perlarchive.com/
CPAN - #1 Perl Resource  (my id:  PINYAN)        http://search.cpan.org/


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe