[8397] in Perl-Users-Digest
Perl-Users Digest, Issue: 2014 Volume: 8
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Mar 3 20:07:44 1998
Date: Tue, 3 Mar 98 17:00:20 -0800
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Tue, 3 Mar 1998 Volume: 8 Number: 2014
Today's topics:
Re: "Learning Perl" or "Programming Perl" scott@softbase.com
Re: [Q] How to redirect STDERR to a subroutine? (Joergen W. Lang)
Re: CO-Branding Web Sites <stacy-lacy@worldnet.att.net>
Re: Conflict in this Newsgroup (Peter G. Martin)
Re: Conflict in this Newsgroup (Joergen W. Lang)
contexts: is there such a thing as array? (Kevin B Cohen)
Re: contexts: is there such a thing as array? <tchrist@mox.perl.com>
Debugging Perl and extensions (Perl gurus please help) gupit@yahoo.com
Detecting Perl version at compile time <rshadian@hawaii.edu>
Re: Killfile Triage (peter caffin)
Re: Killfile Triage (st. paul's wort)
Problems with Win32 Perl and network <paul@geoplex.com>
Re: QUIZ: answer and hash slice tutorial <uri@sysarch.com>
Re: Summing Up Array Values - How Do I? (Douglas Wilson)
Re: The -w switch (was Re: better way to do this?) <tchrist@mox.perl.com>
Re: tr question (Mike Stok)
Re: tr question <stuartc@ind.tansu.com.au>
Digest Administrivia (Last modified: 8 Mar 97) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: 3 Mar 1998 22:06:38 GMT
From: scott@softbase.com
Subject: Re: "Learning Perl" or "Programming Perl"
Message-Id: <6dhute$5vd$1@mainsrv.main.nc.us>
>I'm trying to get started with Perl and I'd like to purchase a book
>from those fine people at O'Reilly but minimize my initial expenses by
>only getting one. My question is "Learning Perl" or "Programming
>Perl"?
>I'm a Windows developer...
Your first Perl stop should be the Win32 version of Learning Perl,
then.
>They both cover a lot of material. Is there much overlap between the
>two? Do they complement each other or offer different things? Is
>"Programming Perl" more advanced, or does it too start from scratch?
Programming Perl is a very advanced reference work. I do not
recommend it for the uninitiated. When you are initiated, though,
it is absolutely indepensible. You'll know when the time to
get this book has come, usually.
>Any thoughts would be appreciated.
I spew forth reviews of many Perl books as part of the Windows 95 Book
FAQ. See the second URL in my signature, and grab the free Cron clone
written in Perl while you're there.
Scott
--
Look at Softbase Systems' client/server tools, www.softbase.com
Check out the Essential 97 package for Windows 95 www.skwc.com/essent
All my other cool web pages are available from that site too!
My demo tape, artwork, poetry, The Windows 95 Book FAQ, and more.
------------------------------
Date: Wed, 4 Mar 1998 00:27:25 +0100
From: joergen.lang@schwaben.de (Joergen W. Lang)
Subject: Re: [Q] How to redirect STDERR to a subroutine?
Message-Id: <1d5c9og.1t2rffa7gr30qN@host016-206.seicom.net>
Mark W. Schumann <catfood@apk.net> wrote:
> I would
> love for the STDERR output to be redirected,
I had a similar situation recently.
The CGI::Carp module has functions for redirecting error messages.
Although I think it was developed to work mostly on web-servers but I
think it might just work fine for you.
=quote (straight from the pod)=
REDIRECTING ERROR MESSAGES
By default, error messages are sent to STDERR. Most HTTPD servers
direct STDERR to the server's error log. Some applications may wish to
keep private error logs, distinct from the server's error log, or they
may wish to direct error messages to STDOUT so that the browser will
receive them.
=end=
Good luck, Joergen
------------------------------
Date: Tue, 03 Mar 1998 18:37:45 -0800
From: Stacy Lacy <stacy-lacy@worldnet.att.net>
To: harrison@pixi.com
Subject: Re: CO-Branding Web Sites
Message-Id: <6di7ur$2n8@bgtnsc03.worldnet.att.net>
Robert F. Harrison wrote:
>
> On Sun, 01 Mar 1998 00:06:55 -0600, digitalstars@yahoo.com
> <digitalstars@yahoo.com> wrote:
> > Does anyone know of a script, or how one would go about co-branding your own
> > web site for someone else? In other words, create an entire new site without
> > the work.
>
> I think simple intellectual theft would suffice in this case, doesn't
> really require Perl. Indeed, that would be overkill.
>
I don't think you really understand the question. Although I don't know
the author, we have a similar need. CO-Branding most likely refers to
the fact that a company may do business under multiple brand names. My
company uses one brand name domestically, and other brand names in
international markets.
------------------------------
Date: 3 Mar 1998 23:08:59 GMT
From: peterm@zeta.org.au (Peter G. Martin)
Subject: Re: Conflict in this Newsgroup
Message-Id: <6di2ib$di9$1@phaedrus.kralizec.net.au>
In article <888954828.55114@thrush.omix.com>,
Zenin <zenin@best.com> writes:
>
> Hmm, what about a different direction. I myself can't stand
> searching the docs by hand, or even with grep/less/web/etc. They also
> don't oftin show any detail on locally installed modules or such
> that may have an answer. If I didn't have Text::English(3)
> installed and with it perlindex(1) I'd go mad.
>
> I would *LOVE* to see Text::English/perlindex as part of the
> standard distribution. A run of perlindex -index as part
> of the install would be needed as well, and if possible an option
> in the perl build config that would add "perlindex -index" to
> root's weekly crontab. I think it would make the newbe excuse of
> too much documentation to search through completely null and void.
> -As the standard distribution is now, I have to say I do think it is
> a valid reason to post an FAQ now and then if you're really new to
> perl.
>
Count this as a "me too". I hate to make a comparison of this kind
but I +will+, just to emphasise the point:
Perl documentation is a bit like M$oft documentation in this sense:
often, it isn't that the information isn't +there+, but rather, clues
to finding it aren't there, or are too limited.
After some years of enthusiastic hacking in perl, I am still at
times confused as to where I'll find the right information within
the docs, and put off by the task for searching through +everything+
to find it... that was, I was, until perlindex. Now I get a list
of clues, and don't run seemingly-infinite recursive grep-like ops
through the doc directories, pod/man pages etc.
Frankly, I'd like to have a similar tool for Linux and its HOW TOs
etc, and keep putting off an examination of the prospects for a
hack or fifty to bring that about. But that's by the by..
OK. If I continue to have the spare time I wish I didn't, I'll
have a go at doing a end-of-book type index for at least some of
the perl docs not otherwise covered for synonym and subject
searching. Looks like a job for FrameMaker there.
But before I start, have I missed something ? Is there an index
of this kind somewhere already ? Or a start to one ?
--
Peter G. Martin, Tech.Writer & Perl User
The Scribe & Chutney Trust
peterm@zeta.org.au, http://www.zeta.org.au/~peterm
ROZELLE, Australia +61 2 9818 5094
------------------------------
Date: Wed, 4 Mar 1998 00:27:22 +0100
From: joergen.lang@schwaben.de (Joergen W. Lang)
Subject: Re: Conflict in this Newsgroup
Message-Id: <1d5c80n.otlgi9bx44uiN@host016-206.seicom.net>
Tom Christiansen <tchrist@mox.perl.com> wrote:
> Fixed in the next release. I'm quite serious -- I did this last week
> or so. The `perl -h' help command will include this line:
>
> -v print version, patchlevel, plus VERY IMPORTANT perl info
>
> Which should prompt them into using:
>
> % perl -v
I'm not so sure if people who don't know about the FAQ will actually get
to the stage of "-h"-ing.
Maybe there is a way of appending a note to the end of the error
message(s) which points people to the FAQ/Documentation/www.perl.com.
Something like:
"If you have any trouble with your script further help can be obtained
by reading the FAQ-files which should be part of your Perl distribution
and/or the Perl-Website www.perl.com (or your nearest Perl Guru?).
Have you tried running your script as 'xyz.pl -w' ?
Have you tried using 'use dignostics;' in your script ?"
Alternatively there could be a pointer within the error message itself
which directs the user to the appropriate FAQ-file.
Just wondering about where people *have to* see this information if they
get an error.
Joergen
------------------------------
Date: 3 Mar 1998 18:37:20 -0500
From: kcohen@julius.ling.ohio-state.edu (Kevin B Cohen)
Subject: contexts: is there such a thing as array?
Message-Id: <6di47g$gdr@julius.ling.ohio-state.edu>
hi,
my basic question: is it Correct to speak of there being such a thing
as array context in perl, as distinct from list context? we learn
early on that there's a difference between scalar context and list
context, and if we've looked on p. 45 of the blue camel we know that
there are different flavors of scalar context:
"Scalar context can be further classified into string context,
numeric context, and don't-care context."
i'm wondering, then, if list context can also be broken down into list
context and array context.
why might we think that this is the case? well, consider the
following (from p. 47 of the blue camel):
@stuff = ("one", "two", "three");
# yes, the blue camel really uses double quotes, as do i...
$stuff = ("one", "two", "three");
# $stuff contains C<three>
$stuff = @stuff;
# $stuff now holds C<3>
different behavior with the array @stuff versus with the list ("one",
"two", "three"), so let's call bread bread and wine wine and conclude
that these are different contexts.
maybe that's not such a good line of argumentation, though. in these
examples, the array and list are on the right-hand side of the
operation, and "context" seems, implicitly, to be determined by the
left-hand side:
"...assignment to a scalar variable evaluates the right-hand side in a
scalar context, while assignemtn to an array or a hash... evaluates
the right-hand side in a list context." (45)
"...the left side of the comma operator provides a void context." (47)
so, consider instead some behavioral differences that we see (or seem
to see; maybe i'm off track) if the array vs. list is on the LHS. if
we have these two things on the left hand side of a match operator, we
can pack a lot more into the array than we can into the list. e.g.:
$string = "It is a truth universally acknowledged";
($one, $two) = /(\w+) (\w+)/g;
print "$one $two\n";
@array = /(\w+) (\w+)/g;
$thing = join(' ', @array);
print "$thing\n";
this produces:
It is
It is a truth universally acknowledged
the list and the array got different things from the match operator:
should we not, then, say that they induce diffferent contexts?
right now you're thinking, "oh, kevin---it's not that the array and
the list impose different contexts, but rather the fact that *they are
different things* that causes them to get different things from the
match operator. the array is a practically bottomless tank, while the
list is a holder for two, and only two, things. no surprise, then,
that their contents are different.
well, maybe you're right. in fact, i think i can give a good argument
for your point of view. consider what happens if that match contains
an optional parenthesized thing that is not present in the string
against which we are matching.in such a case, if in fact there WERE a
real (contextual) difference between list and array contexts, my
expectation is that the list element corresponding to the
optional-and-absent stuff would be undefined; however, i would expect
that the array would have no undefined elements. turns out that the
array does, in fact, seem to have an undefined element:
@array = /(\w+)(\d+\s)(\w+)/;
$thing = join('*', @array);
($one, $two, $three) = /(\w+)(\d+\s)(\w+)/;
print "one: $one two: $two three: $three\n";
print "$thing\n";
this produces:
one: It two: three: is
It**is
so, there doesn't seem to be a difference, here, in the behavior of
the match operator with a list on the LHS, versus with an array on the
LHS.
what's the truth?? are there separate list and array contexts, or am i
full of it?
kevin
------------------------------
Date: 4 Mar 1998 00:31:56 GMT
From: Tom Christiansen <tchrist@mox.perl.com>
Subject: Re: contexts: is there such a thing as array?
Message-Id: <6di7ds$ghn$2@csnews.cs.colorado.edu>
[courtesy cc of this posting sent to cited author via email]
In comp.lang.perl.misc, kcohen@julius.ling.ohio-state.edu (Kevin B Cohen) writes:
:my basic question: is it Correct to speak of there being such a thing
:as array context in perl, as distinct from list context?
No.
:different behavior with the array @stuff versus with the list ("one",
:"two", "three"), so let's call bread bread and wine wine and conclude
:that these are different contexts.
An array behaves differently in scalar context than does a list. That's all.
That doesn't change what a list context is.
--tom
--
Tom Christiansen tchrist@jhereg.perl.com
double value; /* or your money back! */
short changed; /* so triple your money back! */
--Larry Wall in cons.c from the 4.0 perl source code
------------------------------
Date: Tue, 03 Mar 1998 18:09:02 -0600
From: gupit@yahoo.com
Subject: Debugging Perl and extensions (Perl gurus please help)
Message-Id: <6di61r$bee$1@nnrp1.dejanews.com>
Hello,
I am trying to debug an extension I wrote for Perl. The extension is
dynamically loadable. I built a Debugging version of perl (BTW any ideas on
how to "make" a debugging version of perl share the libs etc of an existing
normal version perl binary?) and ran it under gdb. However the function I
wanted to break on in my .xs file is loaded dynamically. Is there a procedure
to be followed to allow setting breakpoints at these type of functions?
I also tried building a statically linked version. It does break, but
somewhere inside the function. Stepping a few times starts the execution
of the function. But it keeps on hanging in the middle. Any ideas?
While I am at it, let me ask the question which prompted me to try to debug
perl.
I am returning a reference to a hash of hashes from a C function. I declared
the top hash mortal.
One of the nested data structure is an array. I create new SV's and push them
in this array. If I create mortal versions of these SV's, I get unknowns in my
perl script.
When I looked at av_push, I found that only the pointer to the SV is stored in
the array entry. That would explain unknown since the SV is freed after my C
functions is returned.
But then when I change the original SV, the array entry doesn't change (whcih
is correct). What exactly happens when I push a scalar and change the scalar?
Is there some magic going on?
Thanks,
Gupit
Thanks in advance,
Gupit
-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/ Now offering spam-free web-based newsreading
------------------------------
Date: Tue, 3 Mar 1998 14:44:39 -1000
From: Ritchard Shadian <rshadian@hawaii.edu>
Subject: Detecting Perl version at compile time
Message-Id: <Pine.GSO.3.95q.980303143618.19096A-100000@uhunix1>
I have a script which includes the "use" declaration to import a couple of
modules. However, when this runs under Perl 4 or earlier, the script will
not compile because "use" is a syntax error in the old Perl. Is there
some way to detect which version of Perl is running before the script is
compiled? It would be better to catch it early and return a nice
formatted error mesage rather than leaving the user to ponder over all the
"syntax error" messages produced when module subroutines are called.
Thank you.
Ritchard
------------------------------------------------------------------------------
Politics is the opposite of progress.
******
------------------------------
Date: Tue, 03 Mar 1998 11:56:37 GMT
From: nospam_synic@omen.net.au (peter caffin)
Subject: Re: Killfile Triage
Message-Id: <34fbee23.345086@news.omen.net.au>
st. paul's wort <rone+usenet@ennui.org> did cunningly address to
comp.lang.perl.misc..
::In article <34f3a2b6.925899@news.omen.net.au>,
::peter caffin <nsynic@omen.net.au> wrote:
::>I simply do not see what the fuss is about. Sighting nospam_ masks in From:
::>headers during a reply is trivial (unless you happen to be writing a
::>spam-bot which does your replying for you).
::
::From: <nsynic@omen.net.au>
::From: <nsynic@omen.net.au>
::From: <nsynic@omen.net.au>
It may interest people to know that the amount of email UCE spam I received
doubled in the 3-4 days after this gimpoid posted my email address in faked
From: headers.
Essentially, I do not believe that posting with a real email address is worth
the increased exposure to UCE email spam. The results from
rone+usenet@ennui.org's posting confirm this totally in my mind.
--: _ ___ _ _ _
_oo__ |_|_ |__ _ | | _ |_|_' _ mailto:synic@omen.net.au
//`'\_ | (/_|(/_| .|. |_(_|| | || | http://www.omen.net.au/~synic
/
------------------------------
Date: 3 Mar 1998 16:44:25 -0800
From: rone+usenet@ennui.org (st. paul's wort)
Subject: Re: Killfile Triage
Message-Id: <rone.TueMar3164227PST1998.8131@ennui.org>
In article <34fbee23.345086@news.omen.net.au>,
peter caffin <nospam_synic@omen.net.au> wrote:
>It may interest people to know that the amount of email UCE spam I received
>doubled in the 3-4 days after this gimpoid posted my email address in faked
>From: headers.
Major bummer!
>Essentially, I do not believe that posting with a real email address is worth
>the increased exposure to UCE email spam. The results from
>rone+usenet@ennui.org's posting confirm this totally in my mind.
You know, this has nothing to do with comp.lang.perl.misc or
news.software.readers, so i've crossposted this (and set followups) to
a more appropriate newsgroup.
rone
--
The finest day that i ever had
Was when i learned to cry on demand
------------------------------
Date: Tue, 03 Mar 1998 14:34:15 -0800
From: Paul Burriesci <paul@geoplex.com>
Subject: Problems with Win32 Perl and network
Message-Id: <34FC8566.D7C83D61@geoplex.com>
We are using the perl5.00402-bindist04-bc distribution of Perl for Win32
under Windows 95.
Colleagues of mine had been using webget.bat (nee webget.pl) to do some
stress testing. I wrote a script using LWP to do a similar thing. The
problem we've been seeing is that Perl's use of network sockets on
Win32 seems to not play nice with other processes (and even, possibly,
itself) also attempting to use sockets. The severity of the problem
seems
to vary from machine to machine, but on one machine while my script
using LWP was running all other network operations were timing out and
Netscape would crash upon launch. After the script was finished
operations returned to normal. The people running stress tests using
webget
would return to find hung machines. I would appreciate enlightenment on
what is going on here if anyone knows.
This is the output from 'perl -w client.pl -i 100 http://www.yahoo.com/
http://www.microsoft.com/' with nothing else using network sockets. The
first 14 iterations ran fine, then iterations 15 through 23 returned
timeouts without actually seeming to wait for a timeout, then the rest
of
the iterations returned 'socket: Bad file number' messages.
Iter 1, http://www.yahoo.com/, Return Code: 200 OK
Iter 1, http://www.microsoft.com/, Return Code: 200 OK
...
Iter 15, http://www.yahoo.com/, Return Code: 408 User-agent timeout
Iter 15, http://www.microsoft.com/, Return Code: 408 User-agent timeout
...
Iter 24, http://www.yahoo.com/, Return Code: 500 socket: Bad file number
Iter 24, http://www.microsoft.com/, Return Code: 500 socket: Bad file
number
...
Iter 100, http://www.yahoo.com/, Return Code: 500 socket: Bad file
number
Iter 100, http://www.microsoft.com/, Return Code: 500 socket: Bad file
number
And this is the script itself:
#!/usr/local/bin/perl -w
use Getopt::Std;
use LWP::UserAgent;
getopts('hri:l:f:p:');
$opt_h and show_usage();
$opt_i = 1 unless $opt_i;
if ($opt_f) {
open URLFILE, "$opt_f" or die "Could not open URL file $opt_f:
$!\n";
@ARGV = <URLFILE>;
for (@ARGV) {
chomp $_;
}
}
show_usage() unless @ARGV;
if ($opt_l) {
open LOGFILE, ">>$opt_l" or die "Could not open logfile $opt_l:
$!\n";
my $date_str = gmtime;
print LOGFILE "\nclient run starting $date_str (GMT)\n",
"$opt_i iteration", ($opt_i > 1) ? "s" : "", "\n",
"URLs:\n";
for (@ARGV) {
print LOGFILE " ", $_, "\n";
}
print LOGFILE "\n";
}
my $ua = new LWP::UserAgent;
$ua->agent("$0/0.1 " . $ua->agent);
$ua->proxy(['http', 'ftp', 'https', 'gopher', 'wais'], "http://$opt_p/")
if ($opt_p);
for (my $i = 0; $i < $opt_i; ++$i) {
for (@ARGV) {
next if /^\s*$/;
$req = new HTTP::Request 'GET' => $_;
$req->header('Pragma' => 'no-cache') if $opt_r;
$req->header('Cache-Control' => 'no-cache') if $opt_r;
$res = $ua->request($req);
print {$opt_l ? LOGFILE : STDOUT} "Iter ", $i + 1, ", $_, ",
"Return Code: ", $res->code,
" ", $res->message, "\n";
}
}
sub show_usage {
die "usage: $0 [-h] [-r] [-i n] [-l file] [-p host:port] <url1> [...
<urln>]\n",
" or: $0 [-h] [-r] [-i n] [-l file] [-p host:port] -f
file\n\n",
" -h: this help message\n",
" -r: reload documents\n",
" -i n: iterate all requests <n> times\n",
" -l file: append results to logfile <file>\n",
" -p host:port: set proxy to <host>:<port>\n",
" -f file: read URLs from <file>\n";
}
___END___
Paul Burriesci
AT&T Labs
paul@geoplex.com
------------------------------
Date: 03 Mar 1998 19:09:28 -0500
From: Uri Guttman <uri@sysarch.com>
Subject: Re: QUIZ: answer and hash slice tutorial
Message-Id: <x73egzz58n.fsf@sysarch.com>
well, it goes to show you that when you try to inject something useful
into this group, it fails. i had only 2 (TWO) respondants to my
quiz. anyway i still decided to write up the answer and some extra
tutorial stuff on the theme. if you find this kind of stuff useful, let
me know and maybe it could be made a (semi) regular kind of post
(especially with help from other perl hackers for quiz ideas and
answers).
the original code was this and i asked what good is it?
@array = qw( a b c d ) ;
@array{ @array } = ( [ @array ] ) x @array ;
there is a very useful perl idiom here which all good perl hackers
should have in their vocabulary. it is called hash slices and it has
many different uses which i will illustrate. it is a rare perl script
(which is not trivially small) that couldn't use hash slices to improve its
efficiency, clarity and elegance.
the fundamental hash slice expression is:
@hash{ @array } = ( list ) ;
this is semantically equivilent to:
( $hash{ $array[0] }, ... $hash{ $array[$#array] } ) = ( list ) ;
that means you are doing an array assignment to a list of entries in the
hash. each entry is indexed by the next array value and is assigned
corresponding value in the list. the list as always can be any
combination of list values and arrays.
the hash slice can be indexed by a list instead of an array but i
haven't found it to be as useful (though it is used sometimes) so i
won't go into it here.
NEWBIE NOTE:
remember that the @ means an array context but it is the {} after the
variable name that marks it as a hash. many newbies fall for this trap.
hashes use {} and arrays use []. when indexing hashes or arrays,
the prefix char is used ONLY to mark context, not data type.
Q: what are the interesting ways of assigning to a hash slice?
the simplest is when you have two arrays of values and you want a hash
to convert a value from one array to another.
@foo_array = qw( abc def ghi ) ;
@bar_array = qw( jkl mno pqr ) ;
@foo_to_bar{ @foo_array } = @bar_array
now you can easily convert from foo values to bar values like this:
$foo_value = 'def' ;
$bar_value = $foo_to_bar{ $foo_value } ;
$bar_value now is 'mno'
you can even convert a whole array of foo values in one statement:
@bar_values = @foo_to_bar{ @foo_values } ;
another very common hash slice idiom i use all the time is testing if a
string is in a given list of strings. we actually don't care about the
values in the hash but i use 1 for clarity and to skip the need for
exists (though exists might be faster. i have never benchmarked it. i
leave that as an assignment for the reader).
@foo_array = qw( abc def ghi ) ;
@is_a_foo{ @foo_array } = (1) x @foo_array ;
$input = 'def' ;
if ( $is_a_foo{ $input } ) {
...
or
if ( exists( $is_a_foo{ $input } ) ) {
...
the assignment uses an interesting operator that most newbies never have
seen. it is called the repetition operator and it is just the plain
letter 'x'. it duplicates its left operand by the numerical value of its
right operand. in a scalar context it replicates its left operand as a
string and returns that. in this case we have a list context and a left
operand of a list, so it creates a new list with N duplicates of the
list. in this case N is 3 (the scalar value of @foo_array) so we get a
list of (1, 1, 1) which is assigned to the hash slice.
a variant on the existance test is conversion from a string to an
numerical index value. we use the range operator (..) to generate the
list of integers which is assigned to the hash slice.
@foo_array = qw( abc def ghi ) ;
for 0 based use:
@foo_to_index{ @foo_array } = ( 0 .. $#foo_array ) ;
for 1 based use:
@foo_to_index{ @foo_array } = ( 1 .. @foo_array ) ;
$i_am_a_foo = 'def' ;
$foo_index = $foo_to_index{ $i_am_a_foo } ;
note that this form can also be used to test if a value is a foo as well
as converting it to an index. remember though that if you use the 0
(zero) based version, you MUST use exists since the value 0 will be
false for the simple test.
NEWBIE NOTE:
notice the selection of names for each of the hashes, %foo_to_bar,
%is_a_foo, $foo_to_index. they are very descriptive of the operation
they perform. in fact i treat them as very fast and simple
subroutines. indexing into a hash is a transformation of the key values
(arguments) to the output values (results). thinking this way will make
your perl scripts much easier to design and write.
now let us look at the original quiz version of the hash slice idiom.
@array{ @array } = ( [ @array ] ) x @array ;
the first thing to notice is that the hash AND the array are both named
array but they are DIFFERENT variables. hashes and arrays (and scalars)
have different nam spaces. i chose the same name to make the quiz a
little trickier. other than that, the left side is just an assignment to
a hash slice, but what is being assigned?
notice that there is the 'x' operator and @array on its right as its
replication count and some list on its left and we are in a list context
(hash slices are list contexts). so we are creating a replicated list of
an anonymous array which contains the values in @array. this means the
hash %array looks like this:
%array = (
'a' => [ 'a', 'b', 'c', 'd' ],
'b' => [ 'a', 'b', 'c', 'd' ],
'c' => [ 'a', 'b', 'c', 'd' ],
'd' => [ 'a', 'b', 'c', 'd' ],
) ;
except that all the anonymous arrays are the same one (the above code
creates 4 different anonymous arrays with the same values).
what good is this structure?
well i was thinking about alias expansion when i devised this. what if
you had a set of aliases and you wanted to expand any one of them to the
full list. this data structure will do that. enter any of the single
elements and you get the entire list. by itself it isn't much but what
if you had multiple sets of aliases? you could do this:
@foo_list = qw( a b c d ) ;
@bar_list = qw( j k l m n o ) ;
@baz_list = qw( w x ) ;
@expand_aliases{ @foo_list } = ( [ @foo_list ] ) x @foo_list ;
@expand_aliases{ @bar_list } = ( [ @bar_list ] ) x @bar_list ;
@expand_aliases{ @baz_list } = ( [ @baz_list ] ) x @baz_list ;
now if you had a single token of unknown type you could get its alias
list in one step:
@aliases = @{ $expand_aliases{ $alias } } ;
or you could build up a list of aliases with this:
foreach $alias ( @in_aliases ) {
push( @out_aliases, @{ $expand_aliases{ $alias } } ) ;
}
NEWBIE NOTE:
the surrounding @{} is used to dereference the stored anonymous list
back into a list for assignment to @aliases.
this is only one way of using this idiom. try to think of others as an
exercise and report them back to me.
lesson is over (for now).
uri
--
Uri Guttman SYStems ARCHitecture and Software Engineering
uri@sysarch.com Have Perl, Will Hack
http://www.sysarch.com (781) 643-7504 x*2 FAX: (781) 643-2710
Try the Best Search Engine on the Net --------> http://www.northernlight.com
------------------------------
Date: Tue, 03 Mar 1998 23:19:37 GMT
From: dgwilson@gte.net (Douglas Wilson)
Subject: Re: Summing Up Array Values - How Do I?
Message-Id: <6di32g$aqj$1@gte2.gte.net>
On 03 Mar 1998 17:44:06 -0500, Uri Guttman <uri@sysarch.com> wrote:
>cberry@cinenet.net (Craig Berry) writes:
>
>> Uri Guttman (uri@sysarch.com) wrote:
>> : let's go schwartzian on the newbie!
>> :
>> : @yards = (2,3);
>> : $sum = 0 ;
>> : map { $sum += $_ } @yards ;
>>
>> Thou shalt not use map in a void context! :) The foreach form is clearer
>> and more efficient:
>
>i agree. i was just showing another way to do it, schwartzian style.
as long as we're being inefficient:
$sum=eval join "+",@yards;
which is incredibly slow.
Cheers,
Douglas Wilson
------------------------------
Date: 4 Mar 1998 00:27:01 GMT
From: Tom Christiansen <tchrist@mox.perl.com>
Subject: Re: The -w switch (was Re: better way to do this?)
Message-Id: <6di74l$ghn$1@csnews.cs.colorado.edu>
[courtesy cc of this posting sent to cited author via email]
In comp.lang.perl.misc, Jon Drukman <jsd@hudsucker.gamespot.com> writes:
:note that the book "effective perl programming" by joseph hall and
:randal schwartz
Randal wrote five pages, so "with" is probably too strongly worded.
:says you should probably turn -w off for production
:programs. (-w is a speed hit and also you don't want your end users
:seeing your warnings.)
That's wrong. Leave them in. If it screws up in production,
you need to know why. Don't remove them.
As for this purported speed hit, show me the numbers. It's
almost if not in fact totally a myth.
--tom
--
Tom Christiansen tchrist@jhereg.perl.com
"Have the appropriate amount of fun." --Larry Wall
------------------------------
Date: 3 Mar 1998 23:24:14 GMT
From: mike@stok.co.uk (Mike Stok)
Subject: Re: tr question
Message-Id: <6di3eu$t5g@news-central.tiac.net>
In article <34FC6D94.630B@wmccmsvr.ssr.hp.com>,
Wayne Patton <wbpatto@wmccmsvr.ssr.hp.com> wrote:
>#!/usr/local/bin/perl
>#
>$_="0000301";
>print "before -> $_\n";
>tr/^0//d;
>print "after -> $_\n";
you probably want to do
s/^0+//d;
which substitutes nothing in place of the beginning of string followed by
one or more 0 characters.
The first argument to tr, which translates (or transliterates) is a
character list e.g.
tr/a-z/A-Z/;
would convert lower case letters to their upper case equivalents (assuming
ASCII). Another example in the debugger:
DB<4> $_ = join ('', 'a' .. 'z', '0' .. '9', '^')
DB<5> print $_
abcdefghijklmnopqrstuvwxyz0123456789^
DB<6> tr/^0//d
DB<7> print $_
abcdefghijklmnopqrstuvwxyz123456789
so the characters ^ and 0 have been deleted.
The first argument to s is a regular expression, and in an regex (outside
of a character class) ^ anchors the match.
These are both documented in the perlop documentation.
Hope this helps,
Mike
--
mike@stok.co.uk | The "`Stok' disclaimers" apply.
http://www.stok.co.uk/~mike/ | PGP fingerprint FE 56 4D 7D 42 1A 4A 9C
http://www.tiac.net/users/stok/ | 65 F3 3F 1D 27 22 B7 41
stok@colltech.com | Collective Technologies (work)
------------------------------
Date: 04 Mar 1998 10:51:14 +1100
From: Stuart Cooper <stuartc@ind.tansu.com.au>
Subject: Re: tr question
Message-Id: <yeovhtv2v0t.fsf@kudu.ind.tansu.com.au>
Wayne Patton <wbpatto@wmccmsvr.ssr.hp.com> writes:
> #!/usr/local/bin/perl
> #
> $_="0000301";
> print "before -> $_\n";
> tr/^0//d;
> print "after -> $_\n";
>
>
> This should strip the leading zeros right?
>
> wayne
Yes, it does. It also strips any other zeros it finds- probably not what
you want.
tr does *not* use regular expressions; and is a charcter-by-character
substitution operation. (eg tr/a-z/A-Z/ for uppercasing).
To strip only the leading zeros; use the regular expression /^0*/ and the
s operator; which does use regualar expressions. You might have thought
you should be using "tr" because you're deleting characters; but what you're
really doing here is deleting characters that match a regular expression- ie
all leading zeros.
English- substitute all-leading-zero-characters with nothing
Perl- s/^0*//;
#!/usr/local/bin/perl
#
$_="0000301";
print "before -> $_\n";
# tr/^0//d; # NO- TRIMS ALL ZEROS
s/^0*//; # YEP
print "after -> $_\n";
Hope this helps,
Stuart Cooper
stuartc@ind.tansu.com.au
------------------------------
Date: 8 Mar 97 21:33:47 GMT (Last modified)
From: Perl-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Digest Administrivia (Last modified: 8 Mar 97)
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". The real FAQ, as it
appeared last in the newsgroup, can be retrieved with the request "send
perl-users FAQ". 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". It appears twice
weekly in the group, but is not distributed in the digest.
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 V8 Issue 2014
**************************************