[13080] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 490 Volume: 9

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Aug 12 19:17:23 1999

Date: Thu, 12 Aug 1999 16:10:17 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Thu, 12 Aug 1999     Volume: 9 Number: 490

Today's topics:
    Re: Sesssion ID <mike@crusaders.no>
    Re: Sesssion ID (Greg Bacon)
    Re: Sesssion ID <tchrist@mox.perl.com>
    Re: String Matching html with indents <v0xman@yahoo.com>
    Re: suggestions for CRAP bane_dewitt@my-deja.com
        Tom Christiansen "Perl Cookbook" support@gethits.com
    Re: while loop teminates too early (Alan Curry)
    Re: Why use Perl when we've got Python?! <arcege@shore.net>
    Re: Why use Perl when we've got Python?! <mcking@cajunbro.com>
    Re: Why use Perl when we've got Python?! <rra@stanford.edu>
    Re: Why use Perl when we've got Python?! <tchrist@mox.perl.com>
    Re: Win32 Perl (newbie) <cassell@mail.cor.epa.gov>
        Digest Administrivia (Last modified: 1 Jul 99) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Fri, 13 Aug 1999 00:09:26 +0200
From: "Trond Michelsen" <mike@crusaders.no>
Subject: Re: Sesssion ID
Message-Id: <tBHs3.683$Sm.5745@news1.online.no>


I R A Darth Aggie <fl_aggie@thepentagon.com> wrote in message
news:slrn7r612r.ht0.fl_aggie@thepentagon.com...
> $sec  = sprintf("%02d",$sec);
> $min  = sprintf("%02d",$min);
> $hour = sprintf("%02d",$hour);
> $mday = sprintf("%02d",$mday);

Ahh - the joy of sprintf() :-) I recently discovered this little beauty in a
script I had to rewrite at work:

return
sprintf("%.2d",$YYYY)."-".sprintf("%.2d",$MM)."-".sprintf("%.2d",$DD)."
".sprintf("%.2d",$hh).":".sprintf("%.2d",$mm).":".sprintf("%.2d",$ss);

It's a good thing the author don't work here anymore, I think I would have
slapped him for that one :-)

But then again - the same file inclues this clueless assignment.

  $YYYY=1900+$YY if($YY>0);

this will of course fail miserably next year (no - $YY is not a return-value
from localtime() )

--
Trond Michelsen





------------------------------

Date: 12 Aug 1999 22:16:05 GMT
From: gbacon@itsc.uah.edu (Greg Bacon)
Subject: Re: Sesssion ID
Message-Id: <7ovh35$cit$1@info2.uah.edu>

In article <tQFs3.122$DI3.11977@typhoon01.swbell.net>,
	snowhare@long-lake.nihongo.org (Benjamin Franz) writes:

: Tom, the phrase 'explaining the obscure via the even more obscure'
: could have been written just for your coding style. Your code is 
: _denser_ - not _clearer_.

You aren't asserting your opinions as fact, are you?  I don't have
problems reading Tom's code (well, except the programm--I think it
was dutree--that cast some really bizarre symbol table magic).  I
also don't believe that denser code is necessarily less clear.
One of Perl's best features *is* its code density.  Instead of
having to go write my own hash and dynamic array libraries, I can
use what Perl provides.  I say

    $hash{key} = 'value';
    $array[42] = 2.71828;

instead of

    hash_insert(hash, "key", value);
    array_insert(array, 42, 2.71828);

These brief examples don't even begin to cover the headaches that
I save myself and the shoulders of giants on which I stand by
taking this path.

The list goes on and on.  Have you ever written network code in C?
Have you done it in Perl?  Which do you prefer and why?

:                           If you step back and ask yourself _why_ 
: seeking out redundancy and factoring it out is ('an' - not 'the') 
: important virtue of a programmer, you will discover your quest for 
: redundancy elimination by any means is misguided.

Here's my scorecard for that round:

    Benjamin - 10
    Strawman -  8

Strawman is out on his feet.  He's not even fighting back.  Someone
should stop this before it's too late! :-)

Regardless of your straw man argument, the process to which Tom refers
is automatic and nearly effortless for experienced programmers.  Good
programmers don't believe in universal overriding goals.  Good
programmers can balance conflicting goals.

:                                                   The goal is to i
: save _overall_ cost - not 'one measure of cost before all others'. 
: 
: Development cost
: Execution cost
: Maintenance cost
: 
: Your style tends to inflate *all* of them. Time for people to
: seek 'perfect' solutions over 'good enough' solutions. Time spent
: in needlessly complex control structures to save a _few_ bytes
: of code for something done only a few times. Time spent by
: maintainers understanding and modifying the code.

Time spent by microoptimization zealots running benchmark after stupid
benchmark to seek 'blazing' solutions over 'fast enough' solutions?

: The highest virtue of a programmer is producing code that does
: the required job with the optimum use of all resources to achieve
: the task. 

I agree with that so long as you include programmer time in the set of
all resources.  I don't consider twiddling with benchmarks to be an
optimum use of my time.

: The original code is fast (faster than all the alternatives
: suggested in this thread with the exception of my own 'show off'
: code), quickly created (it took only seconds), clear, quickly 
: understood and maintained even by novice programmers, 
: and not excessively long. 

Perhaps.  Your approach, however, scales poorly and is not so easy on
the eyes.

: IOW: It is _optimum_.

You need to qualify that.  It's optimum under what set of conditions?

Greg
-- 
>I need to programmatically reboot a Windows NT 4.0 server using Perl.
Any command NT has a certain chance to reboot the machine, hasn't it?
    -- Abigail in <7a01hc$lvb$1@client2.news.psi.net>


------------------------------

Date: 12 Aug 1999 16:48:49 -0700
From: Tom Christiansen <tchrist@mox.perl.com>
Subject: Re: Sesssion ID
Message-Id: <37b34f51@cs.colorado.edu>

     [courtesy cc of this posting mailed to cited author]

In comp.lang.perl.misc, 
    Greg Bacon <gbacon@cs.uah.edu> writes:
:the process to which Tom refers
:is automatic and nearly effortless for experienced programmers.  

Any Perl programmer who advocates:

    for (my $i = 0; $i < @enumeration; $i++) {
	$enumeration[$i] = fn( $enumeration[$i] );
    } 

Above:

    for my $value (@enumeration) {
	$value = fn($value);
    } 

would appear to be trying to program in C, not Perl.

--tom
-- 
Si hoc signum legere potes, 
operis boni in rebus Latinus 
alacribus et fructuosis potiri potes!


------------------------------

Date: Thu, 12 Aug 1999 18:47:07 -0300
From: "Vox" <v0xman@yahoo.com>
Subject: Re: String Matching html with indents
Message-Id: <cgHs3.61165$jl.38602651@newscontent-01.sprint.ca>


Steve Linberg <linberg@literacy.upenn.edu> wrote in message
news:linberg-1208991350500001@ltl1.literacy.upenn.edu...
In article <6DCs3.60923$jl.38427093@newscontent-01.sprint.ca>, "Vox"
<v0xman@yahoo.com> wrote:

> This line here will find it ... if ($line2 =~
> /<!--top-->(.*)<!--bottom-->/s) { .... but there is something wrong
>
> with this line ... $line2 =~
> s/^<!--top-->(.*)<!--bottom-->$/dogsandcats/egimosx; ... in that it won't
    ^                           ^             ^^^^^ ^
    |                           |              \    /
    \------- (clues) -----------/  (all unnecessary in this case)

> recognize the indents or something because it won't replace the indented
> html.

>> That's correct, it's behaving as it should.  See perlre, or the regexep
>> section of the Camel for an explanation of the meanings of ^ and $ in a
>> regexp.  And you should investigate all of your "egimosx" flags at the
end
>> as well, six of which are unnecessary for this example, and two of which
>> contradict each other.

Thank you so much for your clue it worked.  I know that ^ is the beginning
of a line and $ is the end of a line.  I got that from a tutorial but the
tutorial didn't explain what all the flags do except for 'g' which is global
changes every occurrence and ' i ' which ignores case but the rest i just
got out of another free perl program off the net and it worked fine so i
left them there.  At the moment I don't have a perl book so I got to get out
and buy one to have full working knowledge of perl.




------------------------------

Date: Thu, 12 Aug 1999 21:23:23 GMT
From: bane_dewitt@my-deja.com
Subject: Re: suggestions for CRAP
Message-Id: <7ovdvv$oae$1@nnrp1.deja.com>

In article <x7u2q57c0a.fsf@home.sysarch.com>,
  Uri Guttman <uri@sysarch.com> wrote:

> amazing. he actually has the chutzpah to show his face
> here, where he is cursed on a daily basis, where his
> infected code gets trashed because all the newbies can't
> get it to work.

Good for him. :)

--


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.


------------------------------

Date: Thu, 12 Aug 1999 22:24:08 GMT
From: support@gethits.com
Subject: Tom Christiansen "Perl Cookbook"
Message-Id: <37B34B16.D8EC7CF0@gethits.com>

pages 650-3 in "Perl Cookbook" has a recipe 
for using the Mail::Mailer module to send email
through another machine's mail server. Problem is,
I couldnt get it working the way it's suggested in the
book. The code I first tried from the book was:

$mailer = Mail::Mailer->new("smtp", "gethits.mydomain.com");
$mailer->open({    'From'  => $fromemail,
                   'To'    => $email,
                   'Subject' => $subject
                 }) or die "cant open: $!\n";
print $mailer $body;
$mailer->close();


the code that works is below (got this from the module's
documentation):

$mailer = new Mail::Mailer 'smtp', Server => 'gethits.mydomain.com';
$mailer->open({    'From'  => $fromemail,
                   'To'    => $email,
                   'Subject' => $subject
                 }) or die "cant open: $!\n";
print $mailer <<"EOF";

 ... body stuff ...
close($mailer);

Why does the latter work and not the former?

Regards,
Darryl Dyck
GetHits.com


------------------------------

Date: Thu, 12 Aug 1999 21:19:04 GMT
From: pacman@defiant.cqc.com (Alan Curry)
Subject: Re: while loop teminates too early
Message-Id: <cTGs3.472$Rh.27718@typ11.nn.bcandid.com>

In article <MPG.121cd56a86f724d4989e4a@nntp.hpl.hp.com>,
Larry Rosler <lr@hpl.hp.com> wrote:
>Actually, though 'vi' can handle such a file, it complains about 
>'incomplete last line' when the file is loaded in.  So something is 
>amiss with such a file, by my definition, by vi's definition, and (as 
>the rest of the thread shows) by TomC's definition.

There's no disagreement that a text file without a terminating newline is
malformed. The question is what's the best thing to do with this error when
it is detected.

5.003: silently ignore the error and lose data
5.004: force the application programmer to deal with it explicitly
5.005: add an implicit test to handle it

The warning in 5.004 was an improvement over the potential silent corruption
of older versions. Anything, no matter how ugly, is better than silent
corruption!
-- 
Alan Curry    |Declaration of   | _../\. ./\.._     ____.    ____.
pacman@cqc.com|bigotries (should| [    | |    ]    /    _>  /    _>
--------------+save some time): |  \__/   \__/     \___:    \___:
 Linux,vim,trn,GPL,zsh,qmail,^H | "Screw you guys, I'm going home" -- Cartman


------------------------------

Date: Thu, 12 Aug 1999 22:12:32 GMT
From: "Michael P. Reilly" <arcege@shore.net>
Subject: Re: Why use Perl when we've got Python?!
Message-Id: <kFHs3.1651$EG4.312151@news.shore.net>

Tom Christiansen <tchrist@mox.perl.com> wrote:
:      [courtesy cc of this posting mailed to cited author]

: In comp.lang.perl.misc, Ian Clarke <I.Clarke@strs.co.uk> writes:

: :That is not entirely true - I do have an open mind.  The point is that
: :as part of work, I may *need* to write Perl code, and I was really
: :looking for some reasons why this might not be a bad thing... can anyone
: :give me any?

[Clear and proper description of how people view Perl and every thing else
 snipped]

Hi Tom,  I don't usually pipe up to your comments.  You and I have had
our minor bi-/annual debates over Perl vs. Python for some time.  You
always been fair and concise (surprising considering some of the
adversity in the field that both Perl and Python get).  I am a little
surprised at some of your comments below.  You use the idioms common to
Perl to put it in its best light, but fail to use the common idioms for
Python when you are comparing.  Without putting Perl is a bad light,
I'll adjust some of your examples to at least use the idioms in the
Python world.

: The core point of Perl is usefulness.  It's not there to win awards on
: complexity or cleverness or simplicity or minimalism or beauty or any
: other goal that might detract from its real job: helping you get your
: job done by making easy things easy and hard things possible.  Try to 
: keep that in mind.  

: This concept is often expressed as the "Do What I Mean" principle, or in
: short, "DWIM".  When the language tries to do what you want it to do,
: rather than requiring you produce that one exact incantation that will
: accomplish your task, this is DWIM.  DWIM makes the language react to
: the user's expectations, which is nearly the opposite of these stoic and
: spartan dialects, who, in a sad case of the tail wagging the dog, try to
: make the programmer conform to their ideas, not the other way around.
: Making life hard for the programmer and easy for the computer might
: have made sense back when for the price of one computer, you could get
: yourself a score or two of programmers; but today with those ratios
: reversed, it makes little sense.

: The DWIM principle can be found most high-level languages, be these Perl,
: Python, Awk, or BASIC.  In fact, you might even argue that the notions
: of DWIM and high-levelness aren't all that far apart from each other.
: Perl, however, is DWIMmer than Python in several areas that I'm about
: to demonstrate.  Some of Perl's DWIM is really "Do What a Unix Programmer
: Means", but much of it applies to general programming issues irrespective
: of your cultural background.  The amount of dweomercraft required to
: effect this magic is sometimes non-trivial, but the burden rests squarely
: upon the maintainers of the Perl language itself, not upon the writers
: and maintainers of Joe Random Perl code--which is as it should be.

: One place that Perl's dweomer glows is in its automatic conversion between
: character strings and numeric values.  This is something Python doesn't
: do.  Consider what Python does if I feed it 42 on its standard input here:

:     % python
:     >>> import sys
:     >>> n = sys.stdin.readline()
:     42
:     >>> print n + 19
:     Traceback (innermost last):
:       File "<stdin>", line 1, in ?
:     TypeError: illegal argument type for built-in operation

Very true, Python distinguishes between strings and integers and this
sometimes has its affects but it is also not hard to use the built-in
int() function:
      $ python
      >>> import sys
      >>> n = sys.stdin.readline()
      42
      >>> print int(n) + 19
      61

: Perl has no such difficulty, and this we consider a strength.
: If I feed 42 into Perl's standard input for the following code:

:     $n = readline(*STDIN);
:     print $n + 19;

: Then I simply get "61" out my standard output.  It's quite obvious what
: I meant to do, so Perl applies its dweomer to DWIM.

But you could simply think of the "int()" function as a qualifier:  Did
the user really input a number?  Isn't that DWIM as well?

: Another place where Python fails to apply DWIM in numeric values
: is the integer/float boundary.  Python forces the programmer
: to specify whether something is an int or a float.  Perl does not.
: This is good, because usually a programmer just wants a number.
: Consider

:     % echo 'print 3/4' | python
:     0

:     % echo 'print 3/4' | perl
:     0.75

Yes, this is quite deficant of Python in some views (see the multitude
of threads lamenting this by newbies of Python).. fortunately, it is
explained on the first page of really working with Python in the
tutorial (section 3.1.1. "Numbers").

But you could instead type:
      $ echo 'print float(3)/4' | python
      0.75

Again, qualifying what you want.

: Any nine-year old will tell you that three divided by four is 
: three quarters, or 0.75.  Oddly, Python isn't up to the task.
: You'll see the same problem here:

:     >>> n = 400
:     >>> n = n * n; print n
:     160000
:     >>> n = n * n; print n
:     Traceback (innermost last):
:       File "<stdin>", line 1, in ?
:     OverflowError: integer multiplication

True, like most languages, Python integers are limited by the
limitations of the machine.  On most machines this is 32 bits, on some
of the newer machines, it is 64-bits.

: That's because Python seems to want you to type this:

:     % python
:     >>> n = 400.0
:     >>> n = n * n; print n
:     160000.0
:     >>> n = n * n; print n
:     25600000000.0
:     >>> n = n * n; print n
:     6.5536e+20
:     >>> n = n * n; print n
:     4.294967296e+41

Actually, Python prefers you use Long integers, instead of floats:
      $ python
      >>> n = long(400)
      >>> n = n * n; print n
      160000L
      >>> n = n * n; print n
      25600000000L
      >>> n = n * n; print n
      655360000000000000000L
      >>> n = n * n; print n
      429496729600000000000000000000000000000000L

: Perl, however, has no such problem:

:     % perl -d -e 0 
:       DB<1> $n = 400
:       DB<2> $n = $n * $n; print $n
:     160000
:       DB<3> $n = $n * $n; print $n
:     25600000000
:       DB<4> $n = $n * $n; print $n
:     6.5536e+20
:       DB<5> $n = $n * $n; print $n
:     4.294967296e+41

Perl automatically converts the integer to a float, which may not DWIM.

: Or course, a Perl programmer wouldn't write

:     $n = $n * $n

: He'd either write

:     $n *= $n

: or perhaps even

:     $n **= 2

And a Python programmer could write that with:
      n = pow(n, 2)

: This is especially nice for long expressions, such as

:     $n{"alpha"}{"beta"}{"gamma"}{"delta"} **= 2

: The equivalent in Python is the obsequious

:     n["alpha"]["beta"]["gamma"]["delta"] = ( 
:         n["alpha"]["beta"]["gamma"]["delta"] 
:           * 
:         n["alpha"]["beta"]["gamma"]["delta"] 
:     )

: That's quite error prone, because you just had to type the same long thing
: three times.  Perl is safer in this way.  I'll revisit this example later.
: Meanwhile, have fun with your mouse.

True, this is error prone; but more than that, it is multiple
"dereferencing."  The idiom in Python is to write something more like:
    value = n["alpha"]["beta"]["gamma"]
    value["delta"] = value["delta"] * value["delta"]

or even:
    value = n["alpha"]["beta"]["gamma"]
    value["delta"} = pow(value["delta"], 2)

Here you access the "outer" mapping objects only once.

: You also see DWIM behaviour when converting between arrays (what
: you would call lists) and hashes (what you would call dictionaries).
: You can hold a list (what you would call a tuple), and these can be
: automatically converted.   This:

:     @array = ("fred", "wilma", "barney", "betty");
:     %hash  = @array;

: Is the same as:

:     %hash  = ("fred", "wilma", "barney", "betty");

: Because the list stored in the array will have its key-value pairs
: re-interpreted when this is stored into the hash.  

True, but to be fair to both Perl and Python in your context of DWIM:
one thing Perl does not have is the concept of distinct arrays (as
arrays, not references to arrays), or distinct hashs.

Perl will not let you create an array of arrays without a different
syntax.

      @class1 = ("fred", "wilma", "barney", "betty");
      @class2 = ("george", "jane", "judy", "elroy");
      @classes = (@class1, @class2);

Doing what "I would want", I would expect:
      print scalar(@classes), "\n";

to print "2", but instead it prints "8".  To get this you must type:
     @classes = ([@class1], [@class2]);
or:
     @classes = (\@class1, \@class2);
and you must access them differently:
     print ${@{$classes[0]}}[2], "\n";
to print "barney".

And in Python you can:
     >>> foo = [ [], [], [] ]      # same syntax, outer and inner
     >>> print len(foo)
     3

But in Perl:
     DB<1> @foo = ( (), (), () );  # same syntax, outer and inner
     DB<2> print scalar(@foo);
     0
     DB<3> @foo = ( [], [], [] );  # different syntax, outer and inner
     DB<4> print scalar(@foo);
     3

While this is doing what Perl meant, it is not what people expect
without knowing the idioms of Perl.  The same is a problem for hashes.

: Another principle underlying much of Perl is that "things that
: act different should look different".  This allows you to write
: programs in Perl that are *easier* to read, because different things
: don't look like each other.  Python tends to obscure this.

: For example, that's one reason why when you want numeric ordering you
: use "==", but when you want lexical ordering you use an operator that
: looks completely different: "eq".   Likewise, because an array and a hash
: are, despite their interconvertibility, fundamentally different things,
: they *look* different.  Contrast Python's:

:     b = ["alpha", "beta", "gamma"]
:     c = { "fred" : "wilma", "barney" : "betty" }
:     print "b nought is", b[0]
:     print "c fred is", c["fred"]

: with Perl's

:     @b = ("alpha", "beta", "gamma");
:     %c = ( "fred", "wilma", "barney", "betty");
:     print "b nought is", $b[0];
:     print "c fred is", $c{"fred"};

: Or, if you prefer to work only with references (which are like pointers):

:     $b = ["alpha", "beta", "gamma"];
:     $c = { "fred", "wilma", "barney", "betty"};
:     print "b nought is", $b->[0];
:     print "c fred is", $c->{"fred"};

: Accessing an array and accessing a hash are different operations.
: They look very different.  It's obvious to the reader what's going on.
: They can look at %h and @a and know these are different.
: They can look at $h{"fred"}" and $a[0] and know these are different.

But Tom, how different do they look?  Take for example:
      @a = ("fred", "wilma", "pebbles", "dino");
      %a = (0, "george", 1, "jane", 2, "judy", 3, "elroy");
      print "a nought is", $a[0];
      print "a nought is", $a{0};

This can be confusing too.  Get a bad font on the editor and a square
bracket will look like a curly bracket.  It still requires knowing the
language and understanding the code.

: Another place is quotes.  Single quotes look different from double quotes.
: And they do very different things: the former is an uninterpolated
: literal, whereas the latter expands variables and C-style backslash
: escapes.

Very true.  In Python, double quotes work like single quotes, and both
work more like C-style.  (Python recently (18 months) added "raw
strings" which do not even perform the the C-style baskslash escapes.)

: Perl consistently produces better error messages than Python. 
: Here's one example:

:     % echo 'print f()' | python
:     Traceback (innermost last):
:       File "<stdin>", line 1, in ?
:     NameError: f

:     % echo 'print f()' | perl
:     Undefined subroutine &main::f called at - line 1.

: After a while, you just want to take all your mysterious "name errors"
: and "syntax errors" and send them one at a time to Guido.

Oh yes.  No argument there, Perl has much better built-in error
messages.  But I guess you didn't want to discuss user errors, so I
won't get into eval vs. try-except.  That can be for another time. :)

: Let's finish up go back to DWIM.  Python is really not very good at 
: autoallocation, at least when compared to Perl.  Consider for example:

:     @array = ("alpha", "beta", "gamma");
:     $array[3] = "delta";

: That's just fine in Perl.  It's not fine in Python, because Python
: won't automatically grow an array.  

:     >>> a = ["alpha", "beta", "gamma"]
:     >>> a[3] = "delta"
:     Traceback (innermost last):
:       File "<stdin>", line 1, in ?
:     IndexError: list assignment index out of range

: Instead, you need to remember to use

:     a.append("delta")

: if it doesn't exist yet.  This complexity forces the programmer who wants
: to assign "delta" to the third slot (there's a zeroth slot) of the list
: (Python parlance) to do something totally different in one situation
: than they have to do in another.

Yes, autoexpansion is not part of Python.  It was designed not to have
it, but what it does have is some other features, like replication,
concatenation, comparison.  Also, it is pretty trivial to make a
subclass of UserList to include autoexpansion if it is needed.

: In Perl, this is much easier.  In fact, it just does what you mean
: right from the start.  

: Oddly enough, Python does let you grow dictionaries automatically.
: In fact, you have to do so.  Even though they are initialized
: differently

:     a = ["alpha", "beta", "gamma"]
:     d = {"fred": "wilma", "barney": "betty"}

: But they look the same on access:

:     print a[0]
:     print d["fred"]

: You aren't able to add something to them the same way.  For
: adding a new slot to the dictionary where there wasn't one, 
: you can just use

:     d["more"] = "stuff"

: but the list requires a completely different syntax.  In fact,
: it requires a function call!  And you can't call

:     d.append("more" : "stuff")

This is misleading, Tom.  You can do the same without a "function call".
      a = a + ["stuff"]

Python allows concatenation of sequences (lists, tuples, strings).

And you are mixing your statements here. the d.append statement would
be: d.update( {"more": "stuff"} )

: Perl is much more consistent here than Python is.

Come now, Tom.  You know better than this; this is the difference
between arrays/lists and hashes/dictionaries.  Perl is no more
consistant than C is declaring multidimensional arrays.  This is no
less confusing then using:
   %person = ("name", "Michael", "nick", "Arcege", "age", 30);
   $person{"company","position"} = "Release Manager"
   @whatisthis = @person{"name","nick"};
   $whatisthis = $person{"name","nick"};

Python defines three basic interfaces: numbers (integers, long integers,
floats and complex numbers), sequences (strings, tuples, lists) and
mappings (dictionaries).  There are similarities and differences between
them, indexing being one similarity.

In every language, there will be idiosyncrasies.

: Finally, consider this code in Perl.  This is a complete
: program.

:     $n{"alpha"}{"beta"}{"gamma"}{"delta"} = 400;
:     $n{"alpha"}{"beta"}{"gamma"}{"delta"} **= 2;
:     print $n{"alpha"}{"beta"}{"gamma"}{"delta"}, "\n";

: Grab your mouse and do the old snarf-and-barf into Perl.  You'll see
: that it prints 160000 as we saw before.

: To do the equivalent in Python is remarkably more tedious.

:     n = {}
:     n{"alpha"} = {}
:     n["alpha"]["beta"] = {}
:     n["alpha"]["beta"]["gamma"] = {}
:     n["alpha"]["beta"]["gamma"]["delta"] = 400
:     n["alpha"]["beta"]["gamma"]["delta"] = ( 
:         n["alpha"]["beta"]["gamma"]["delta"] 
:           * 
:         n["alpha"]["beta"]["gamma"]["delta"] 
:     )
:     print n["alpha"]["beta"]["gamma"]["delta"] 

: Notice all those steps you have to go through?  It's true that
: you can get by with just

:     n = {'alpha': {'beta': {'gamma': {'delta': 400}}}}

Thank you for this... I knew you were fair. ;)

: But the point is that Python refused to autoallocate for you. 
: You have to do all the hard work on your own.  Perl, on the other
: hand, is much more helpful here, applying DWIM to do what you meant.

For many, DWIM is perfectly applicable here.  Some programers desire
the checks that variables are defined before using them, that
subscripts exists when accessing them, that keys are in a hash when you
want them; this is the reason "exists" was added to Perl 5 after all,
no?

: And if you think that the dictionary example is rough, consider
: this Perl code:

:     $n[20][20][20][20] = 400;
:     $n[20][20][20][20] **= 2;
:     print $n[20][20][20][20], "\n";

: Because a Python list can't grow by direct assignment the way
: a Perl array, a Python dictionary, or a Perl hash can, you can't
: just do repeated assignments in Python like

:     n = []
:     n[20] = []
:     n[20][20] = []
:     n[20][20][20] = []
:     n[20][20][20][20] = 400

: That still won't work, of course.  

True, this is a limitation in Python.  Not because of autoexpansion,
but because of creation of lists accessing references.  The above should
be rewritten as:
      n = [None] * 21
      n[20] = [None] * 21
      n[20][20] = [None] * 21
      n[20][20][20] = [None] * 21
      n[20][20][20][20] = 400

But then anyone with some knowledge of computer science would tell you
to make a sparce matrix instead of this super huge, multidimensional
array.  But then, there are also modules to handle these kinds of
things, nicely and efficiently.

: I've typed for you all morning long.  I hope that this gives you a feel
: for some fundamental ways where Perl is more programmer-friendly than
: Python is.  There are others, such as scoping issues, but these should
: suffice to provide you something of the flavor.

: --tom

Boy it's good to get back in it with you again, Tom; even if it is only
a brief, simple debate every couple of years.  It's been a while. :)

  -Arcege

PS: Going to the O'Reilly OSS Convention?



------------------------------

Date: Thu, 12 Aug 1999 22:36:52 +0000
From: Mark McCoy <mcking@cajunbro.com>
Subject: Re: Why use Perl when we've got Python?!
Message-Id: <37B34C84.E0720658@cajunbro.com>

Tom,

I thought I posted long messages!!  :)

I bow to your Perl guru-hood though.  This set of comparisons makes me glad I
never spent the time to do more than glance at python.

"Perl is the Cliff's Notes of Unix" - I think should be "Perl is the Cliff's
Notes of C/C++".  At least that is how I generally use it.  It amazes me that
after 50 years of computer language research, we still have C/C++ programmers
reimplementing dynamically allocated lists and hashes in hundreds of different
ways, modifying them each time because they don't quite fit the situation,
causing all sorts of memory leaks and wasted effort.  String handling, pattern
matching and other features of Perl are all bonuses, because while I could
implement a specialized pattern matching algorithm for a particular program, why
should I have to?  I am here to solve problems,  move data around, grind it up,
and spit it out -- not waste time fiddling with linked lists and malloc, etc...

I love the whole DWIM argument as well (although DWIM is not always the case
when I am picking up some new aspect of Perl!!).  That alone is reason to use
Perl.


-- 
Mark McCoy -- Cajun Brothers Technology, llc
Proud to run Linux since February 1996
This message posted from snowdog, a 100% MS-free machine.
The views in this message do not necessarily reflect the views of my employe


------------------------------

Date: 12 Aug 1999 15:21:40 -0700
From: Russ Allbery <rra@stanford.edu>
Subject: Re: Why use Perl when we've got Python?!
Message-Id: <ylwvv0y70r.fsf@windlord.stanford.edu>

Ian Clarke <I.Clarke@NOSPAM.strs.co.uk> writes:

> I agree that conflict won't bring understanding, but I was hoping that
> people familiar with the language could explain what is good about Perl,
> without trying to start a conflict.

You're doing the equivalent of asking people to describe to you why you
might want to eat ice cream, in detail, while never taking a bite
yourself.  I really don't know how you'd expect people to be able to do
that.

What's good about Perl is that after I learned it, I found I enjoyed
writing programs in it more than any other language.  There's something
about Perl that gives the programmer pleasure in finding a particularly
clear way of expressing an idea, or a particularly effective use of data
structures, that I haven't found elsewhere.  How can I describe that to
you if you don't actually try the language with an open mind?

Perl certainly isn't Python.  It isn't even remotely like Python.  If you
look at it, expecting it to be Python, you'll hate it.  Comparing
languages is frankly not something I'd recommend anyone do, since the
outcome depends on how and what you're thinking when you do it.  There are
times when I think FORTRAN is really elegant, or that BASIC had some great
concepts.

Despite how much other people are trying, I think your questions are
unanswerable in the way that you're phrasing them.  Maybe you won't be one
of the people who likes Perl.  There certainly are programmers who don't
think like Perl does.  And there are people who do.

People who know Perl find it readable, fairly easy to debug, and fairly
straightforward in most of its aspects, despite the complexity of the
language.  People who don't know Perl don't.  Perl is not a language
designed for the people who don't know it very well, whereas Python is
much more welcoming.

Perl is the antithesis of LISP, although you can write LISP in Perl.

Perl is like the AutoCAD of programming languages.  You don't pick it up
casually in an afternoon to throw together a quick sketch of your garden.
You invest time, blood, sweat, and tears into learning an occasionally
arcane syntax and odd features designed to do what the experienced
programmer wants, which you aren't yet, and which therefore often badly
misguess your intentions, until one day you hit the knee in the curve,
start the exponential climb, and wonder why you ever even bothered with
another scripting language.

Or maybe you don't.  I can only speak for me.  :)

-- 
#!/usr/bin/perl -- Russ Allbery, Just Another Perl Hacker
$^=q;@!>~|{>krw>yn{u<$$<[~||<Juukn{=,<S~|}<Jwx}qn{<Yn{u<Qjltn{ > 0gFzD gD,
 00Fz, 0,,( 0hF 0g)F/=, 0> "L$/GEIFewe{,$/ 0C$~> "@=,m,|,(e 0.), 01,pnn,y{
rw} >;,$0=q,$,,($_=$^)=~y,$/ C-~><@=\n\r,-~$:-u/ #y,d,s,(\$.),$1,gee,print


------------------------------

Date: 12 Aug 1999 16:46:52 -0700
From: Tom Christiansen <tchrist@mox.perl.com>
Subject: Re: Why use Perl when we've got Python?!
Message-Id: <37b34edc@cs.colorado.edu>

     [courtesy cc of this posting mailed to cited author]

In comp.lang.perl.misc, "Michael P. Reilly" <arcege@shore.net> writes
various things.

:You use the idioms common to
:Perl to put it in its best light

Of course.  I interpreted the question to be "where does Perl look good
compared with Python?"

:but fail to use the common idioms for
:Python when you are comparing.  

I certainly used some of them.  And I intentionally avoided others,
because they lose the spirit.

:Very true, Python distinguishes between strings and integers and this
:sometimes has its affects but it is also not hard to use the built-in
:int() function:

:      $ python
:      >>> import sys
:      >>> n = sys.stdin.readline()
:      42
:      >>> print int(n) + 19
:      61

No, it is not hard.  But neither is it sensible to a Perl programmer.
Why do I care whether it's anything but a number?  I didn't ask to convert
to an integer, and I didn't want to.  I wanted the user to be able to
enter any kind of number, without worrying about machine representation.
It's a higher level of abstraction.  Notice how if you enter 41.5 to
Python above the herpetarium escapee spits a venomous exception in my eye.
What did I do to deserve that?  

:But you could simply think of the "int()" function as a qualifier:  Did
:the user really input a number?  Isn't that DWIM as well?

When I say "+", I'm indicating that it's a number.  I certainly
don't expect to the statement to fail spectacularly merely because
of one machine representation or another.

:But you could instead type:
:      $ echo 'print float(3)/4' | python
:      0.75
:
:Again, qualifying what you want.

Yes.  I know you can do that.  I don't *want* to do that.  It's not
something I think the programmer should by default concern themselves
with, anymore than they should have to think about whether their ints
are 16, 32, or 64 bits in length.  

My goal was to show why Perl's DWIM principle made these things
easier than in Python.

:True, like most languages, Python integers are limited by the
:limitations of the machine.  On most machines this is 32 bits, on some
:of the newer machines, it is 64-bits.

But we promote.  We try hard to present the notion that what we have
here is simply numbers, which is what people care about, not anything
bitwise that the machine cares about.

:True, this is error prone; but more than that, it is multiple
:"dereferencing."  The idiom in Python is to write something more like:
:    value = n["alpha"]["beta"]["gamma"]
:    value["delta"] = value["delta"] * value["delta"]

If you wanted to go that route, I could have shown the idiom in Perl of

    for $href ($n{"alpha"}{"beta"}{"gamma"}) {
	$href->{"delta"} **= 2;
    } 

or even 

    for $num ($n{"alpha"}{"beta"}{"gamma"}{"delta"}) {
	$num **= 2;
    } 

:True, but to be fair to both Perl and Python in your context of DWIM:
:one thing Perl does not have is the concept of distinct arrays (as
:arrays, not references to arrays), or distinct hashs.

Well, @a is a distinct array, and %h a distict hash.  The issue is
that an array is different from a reference thereto, and likewise
for all other thingamawhatsits.

:Perl will not let you create an array of arrays without a different
:syntax.

More properly, an array of array references.  Since an array and an
array reference are different, this is not very surprising.

:and you must access them differently:
:     print ${@{$classes[0]}}[2], "\n";
:to print "barney".

MY GOD MAN!  If I had to do that, Of course I'd run screaming
to Python.  But you don't have to do that.  

    $classes[0][2]

is just fine.  Don't make things harder on yourself than you need to.

:This can be confusing too.  Get a bad font on the editor and a square
:bracket will look like a curly bracket.  It still requires knowing the
:language and understanding the code.

Most things do.

:: And they do very different things: the former is an uninterpolated
:: literal, whereas the latter expands variables and C-style backslash
:: escapes.
:
:Very true.  In Python, double quotes work like single quotes, and both
:work more like C-style.  (Python recently (18 months) added "raw
:strings" which do not even perform the the C-style baskslash escapes.)

We had them in 1987. :-)

:Yes, autoexpansion is not part of Python.  It was designed not to have
:it

Sometimes yes, sometimes no.  It's designed to do so for dictionaries
but not lists.  

:For many, DWIM is perfectly applicable here.  Some programers desire
:the checks that variables are defined before using them, that
:subscripts exists when accessing them, that keys are in a hash when you
:want them; this is the reason "exists" was added to Perl 5 after all,
:no?

Having to grow things is the issue.  I have to grow an integer into
a float.  The language won't do that for me.  But I don't have to grow
a string.  I have to grow a list in order to add something to it.
But I don't have to grow a dictionary.  I absolutely cannot see why
assigning to a non-existent element of a list triggers an exception,
whereas doing so to a dictionary will auto-allocate.  In Perl, both
operations cause the same thing.

Python is much more "my way or die".  If you do something it feels the
least bit nervous about, it raises an exception, and it's all over.
Perl, on the other hand, given a dodgy situation, punts.  It tries DWIM,
and failing that, may emit a warning.  Its fail-soft behaviour is rather
more forgiving.

Perl even autovivifies something like

    undef $a;
    $a->[23] = "fred";

You will find tht $a now contains an array reference.  That it does
so in lvalue context is a blessing; that it shoudl also do so in rvalue
context is arguable.

As I said at the outset, what one side considers a strength, the other
often considers a weakness.  Perl's stragegy of DWIM with respect
to auto-allocation and conversions between strings and numbers, and
within numbers, between ints and floats, is considered a good one by
Perl programmers.  We don't want bondage-and-discipline languages.

::     n[20][20][20][20] = 400
:: That still won't work, of course.  
:
:True, this is a limitation in Python.  Not because of autoexpansion,
:but because of creation of lists accessing references.  

If I'm understanding what you're saying, that still falls in the category
of auto-allocation in my book.

:The above should
:be rewritten as:
:      n = [None] * 21
:      n[20] = [None] * 21
:      n[20][20] = [None] * 21
:      n[20][20][20] = [None] * 21
:      n[20][20][20][20] = 400

I didn't say it was impossible.  But I still deem it unpleasant in
the extreme.

:PS: Going to the O'Reilly OSS Convention?

Surely.

--tom
-- 
    Real Programmers think better when playing Adventure or Rogue.


------------------------------

Date: Thu, 12 Aug 1999 14:17:25 -0700
From: David Cassell <cassell@mail.cor.epa.gov>
Subject: Re: Win32 Perl (newbie)
Message-Id: <37B339E5.72377D92@mail.cor.epa.gov>

James Liu wrote:
> 
> I got Oreilly's Learning Perl (Llama book).  I'm running Windows 98.  what
> should I know about how perl runs on windows? please help.

In addition to Lauren's advice to get ActiveState Perl [build 518
now], I recommend that you go trade that llama for a gecko.
Get "Learning Perl on Win32 Systems" by Randal Schwartz, Erik
Olson, and, hmmm.. let's see.. oh some guy who hates win32.  
:-)

David
-- 
David Cassell, OAO                     cassell@mail.cor.epa.gov
Senior computing specialist
mathematical statistician


------------------------------

Date: 1 Jul 99 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 1 Jul 99)
Message-Id: <null>


Administrivia:

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

To submit articles to comp.lang.perl.misc (and this Digest), send your
article to perl-users@ruby.oce.orst.edu.

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.

The Meta-FAQ, an article containing information about the FAQ, is
available by requesting "send perl-users meta-faq" from
almanac@ruby.oce.orst.edu. The real FAQ, as it appeared last in the
newsgroup, can be retrieved with the request "send perl-users FAQ" from
almanac@ruby.oce.orst.edu. Due to their sizes, neither the Meta-FAQ nor
the FAQ are included in the digest.

The "mini-FAQ", which is an updated version of the Meta-FAQ, is
available by requesting "send perl-users mini-faq" from
almanac@ruby.oce.orst.edu. 

For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V9 Issue 490
*************************************


home help back first fref pref prev next nref lref last post