[23572] in Perl-Users-Digest
Perl-Users Digest, Issue: 5779 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Nov 11 06:05:51 2003
Date: Tue, 11 Nov 2003 03:05:07 -0800 (PST)
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, 11 Nov 2003 Volume: 10 Number: 5779
Today's topics:
Re: binary dist calculation <steffen.beyer@de.bosch.com>
Calling a sub in main script from module (fatted)
Re: count of 1s in a binary number <steffen.beyer@de.bosch.com>
Re: count of 1s in a binary number <steffen.beyer@de.bosch.com>
How to simulate keyboard.../dev/tty0? <keeper@iosys.no-ip.org>
Re: installing perl <usenet@morrow.me.uk>
JVM in perl <Mc-Kiernan@bogus-subdomain.worldnet.att.net>
Re: LWP::UserAgent and SSL is it impossible? <HelgiBriem_1@hotmail.com>
Re: Perl Newbie <tore@aursand.no>
Re: Perl Newbie <ak+usenet@freeshell.org>
Posting Guidelines for comp.lang.perl.misc ($Revision: tadmc@augustmail.com
Re: simplify this if loop <tore@aursand.no>
Re: Sort array of objects using a method <tassilo.parseval@rwth-aachen.de>
Re: Style question: map versus foreach <tassilo.parseval@rwth-aachen.de>
Re: Style question: map versus foreach <usenet@morrow.me.uk>
Re: Style question: map versus foreach <tassilo.parseval@rwth-aachen.de>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Tue, 11 Nov 2003 10:48:21 +0100
From: "Steffen Beyer" <steffen.beyer@de.bosch.com>
Subject: Re: binary dist calculation
Message-Id: <boqb97$pus$1@ns2.fe.internet.bosch.com>
"Fred" <fJogham@yahoo.com> wrote in message =
news:3FABD5EF.8050201@yahoo.com...
> Hello
> I am trying to calculate the distance between 2 binary data arrays
> it is puting out errors but I don't know why or how to fix it.
> I guss if I spend a day or 2 reading I may know why and fix it but =
after=20
> 1/2 hr or trail and error I gave up.
>=20
> thanks
>=20
> my @bit1 =3D qw /01 10 01 01 01/;
> my @bit2 =3D qw /01 00 11 01 00/;
> print (dist(\@bit1, \@bit2), "\n"); pass array ref to sub
>=20
> sub dist {
> my $fst =3D shift; #grab the first array
> my $x =3D join("", @{$fst}); #de-ref into a string
> my $X =3D "0b$x"; #concate "0b" infront for the "^" xOR operator
> my $scd =3D shift;
> my $y =3D join("", @{$scd});
> my $Y =3D "0b$y";
> my $answer =3D sprintf "%b", $X ^ $Y; #xOR($X, $Y)
> return ($answer =3D~ tr/1//); #grab how many 1s
> }
As "There Is More Than One Way To Do It" (TIMTOWTDI) in Perl,
here another solution, which has the advantage of being quite fast, =
especially
for large bit vectors (the bit counting is also very efficient here):
#!perl -w
use strict;
use Bit::Vector;
my @bit1 =3D qw /01 10 01 01 01/;
my @bit2 =3D qw /01 00 11 01 00/;
print (dist(\@bit1, \@bit2), "\n");
sub dist
{
my($a,$b);
$a =3D Bit::Vector->new(32);
$b =3D Bit::Vector->new(32);
$a->from_Bin(join('', @{$_[0]}));
$b->from_Bin(join('', @{$_[1]}));
$a->Xor($a,$b);
return $a->Norm();
}
Hope this helps!
Cheers,
Steffen
------------------------------
Date: 11 Nov 2003 02:57:14 -0800
From: obeseted@yahoo.com (fatted)
Subject: Calling a sub in main script from module
Message-Id: <9edc36a2.0311110257.53a1be77@posting.google.com>
Having called a function from a module, I'd like that module function
to call a function from the main script, but I can't figure out how
(had a look through perlsub, perlmod,...)
Simple Example:
####### script.pl
#!/usr/bin/perl
use warnings;
use strict;
use Readable;
my $file = 'not_there.txt';
file_readable($file);
sub write_log
{
my $msg = shift;
print $msg."\n";
}
###### Readable.pm
package Readable;
use Exporter;
@ISA = ('Exporter');
@EXPORT = qw(&file_readable);
sub file_readable
{
my $file = shift;
open(IN,"<",$file) or $main::write_log("No thanks");
}
1;
######
When I run script.pl, I get:
syntax error at Readable.pm line 9, near "$main::write_log("
Compilation failed in require at ./script.pl line 5.
BEGIN failed--compilation aborted at ./script.pl line 5.
Whats the correct way to do this?
While we're here, if, use strict; use warnings; are used in a script
does this apply to any modules which are included by the script (via
use)?
------------------------------
Date: Tue, 11 Nov 2003 11:03:53 +0100
From: "Steffen Beyer" <steffen.beyer@de.bosch.com>
Subject: Re: count of 1s in a binary number
Message-Id: <boqc6b$qnq$1@ns2.fe.internet.bosch.com>
"Anno Siegel" <anno4000@lublin.zrz.tu-berlin.de> wrote in message =
news:boj8vt$iui$1@mamenchi.zrz.TU-Berlin.DE...
> Putting it together:
>=20
> sub size2 {
> my $n =3D shift;
> my $size =3D $n ? 1 : 0;
> $size++ while $n ^=3D (($n - 1) ^ $n) & $n;
> $size;
> }
Note that the "XOR" operation is superfluous.
This also works (C code):
int c =3D 0xDEADBEEF; /* or whatever */
int count =3D 0;
while (c)
{
c &=3D c - 1;
count++;
}
Should work similarly in Perl.
BTW, that's exactly what the module "Bit::Vector" uses internally.
So here is another solution (TIMTOWTDI):
#!perl -w
use strict;
use Bit::Vector;
my $bit1 =3D "011001010";
my @bit2 =3D qw /01 00 11 01 00/;
print size_of($bit1), "\n";
print size_of(@bit2), "\n";
sub size_of
{
my($vec) =3D Bit::Vector->new(32);
$vec->from_Bin(join('', @_));
return $vec->Norm();
}
Hope this helps!
Cheers,
Steffen
------------------------------
Date: Tue, 11 Nov 2003 11:30:28 +0100
From: "Steffen Beyer" <steffen.beyer@de.bosch.com>
Subject: Re: count of 1s in a binary number
Message-Id: <boqdo5$s9l$1@ns2.fe.internet.bosch.com>
Here's another benchmark of the various solutions,
with a slightly improved size_trick and a new size_bitvec,
performed under Windows 2000 with a native build of
Perl 5.8.0:
C:\>perl bench.pl
Benchmark: timing 500000 iterations of size_bitvec, size_pack, size_rec, =
size_tr, size_trick...
size_bitvec: 2 wallclock secs ( 1.80 usr + 0.00 sys =3D 1.80 CPU) @ =
278241.51/s (n=3D500000)
size_pack: 0 wallclock secs ( 1.41 usr + 0.00 sys =3D 1.41 CPU) @ =
355366.03/s (n=3D500000)
size_rec: 33 wallclock secs (34.02 usr + 0.00 sys =3D 34.02 CPU) @ =
14699.40/s (n=3D500000)
size_tr: 5 wallclock secs ( 4.61 usr + 0.00 sys =3D 4.61 CPU) @ =
108483.40/s (n=3D500000)
size_trick: 8 wallclock secs ( 8.69 usr + 0.00 sys =3D 8.69 CPU) @ =
57557.27/s (n=3D500000)
Rate size_rec size_trick size_tr size_bitvec =
size_pack
size_rec 14699/s -- -74% -86% -95% =
-96%
size_trick 57557/s 292% -- -47% -79% =
-84%
size_tr 108483/s 638% 88% -- -61% =
-69%
size_bitvec 278242/s 1793% 383% 156% -- =
-22%
size_pack 355366/s 2318% 517% 228% 28% =
--
And here's the program:
#!perl -w
use strict;
use warnings;
use Bit::Vector;
use Benchmark qw/:all/;
my $max=3D ~0;
my $vec =3D Bit::Vector->new(Bit::Vector->Word_Bits());
my $res=3Dtimethese (500000, {
'size_rec' =3D> "size_rec(int rand $max)",
'size_tr' =3D> "size_tr(int rand $max)",
'size_trick' =3D> "size_trick(int rand $max)",
'size_pack' =3D> "size_pack(int rand $max)",
'size_bitvec' =3D> "size_bitvec(int rand $max)",
});
cmpthese($res);
sub size_rec {
my $n=3Dshift;
return 0 unless $n;
return ($n&1) + size_rec($n>>1);
}
sub size_tr {
qq.@{[map sprintf('%b',$_),@_]}. =3D~ tr/1//;
}
sub size_trick {
my $n =3D shift;
my $size =3D 0;
$size++ while $n &=3D $n-1;
$size;
}
sub size_pack {
my $x =3D shift;
unpack '%32b*', pack 'I', $x;
}
sub size_bitvec {
$vec->Word_Store(0,$_[0]);
$vec->Norm();
}
__END__
------------------------------
Date: Tue, 11 Nov 2003 09:42:31 +0100
From: Keeper <keeper@iosys.no-ip.org>
Subject: How to simulate keyboard.../dev/tty0?
Message-Id: <boq7e6$a0$1@atlantis.news.tpi.pl>
Hi all,
I'm trying to send chars to the current console (currently having cursor
focus) - /dev/tty0 - in my program by:
my $st = 'K'
my $ri = 'L'
my $ng = 'J'
open(TTY, ">/dev/tty0");
ioctl(TTY, &TIOCSTI, $st);
ioctl(TTY, &TIOCSTI, $ri);
ioctl(TTY, &TIOCSTI, $ng);
I'm using redhat 9, kde.
Everything is ok in the linux console (on tty1 chars are sending
properly - KLJ...), but in kde i see strange things (and not only for
those characters):
^[[D- on ttyp1
- on mozilla window
My question is why chars are not properly sending by ioctl call, is
there any additional settings to do (setting termios, keyboard driver?)??
thanks,
Keeper
------------------------------
Date: Tue, 11 Nov 2003 08:47:49 +0000 (UTC)
From: Ben Morrow <usenet@morrow.me.uk>
Subject: Re: installing perl
Message-Id: <boq7nl$6pl$1@wisteria.csv.warwick.ac.uk>
news@group.com wrote:
> >>Ben Morrow wrote:
> > OK... you used Configure -d, so it took all default answers.
> > Check for me: after running Configure, config.sh contains
> > prefix='/usr/local'
> > and
> > installprefix='/usr/local'
> > ?
>
> Yes, both point to /user/local. BUT after I did the following steps.
> I put back the symlink pointing to perl5.6.1:
> rm /usr/bin/perl;
> ln -s perl5.6.1 /usr/bin/perl
> :/home/username/#/usr/bin/perl5.6.1
> print 1\n;
> 1
Nonono, that doesn't matter at all.
> Once things stabilized,
What do you mean by that?
> I went back to perl-5.8.1 directory and start
> over, but left out the -de
> reboot into a new root shell, no kde or x environment.
> :/home/username/#tar -zxvf stable.tar.gz
> :/home/username/#cd perl-5.8.1
> :/home/username/perl-5.8.1#rm -f config.sh Policy.sh
Again, you're issuing commands you don't (appear to) understand. There
*is* no config.sh or Policy.sh in the distributed tarball, so you
don't need to delete them.
> :/home/username/perl-5.8.1#sh Configure
> accept all the defaults except
> Directories to use for library searches? [/usr/local/lib /lib /usr/lib]
> /usr/local/lib
Why did you do that? Did you understand the question? It has nothing
to do with Perl modules: it has to do with where the linker searches
for C libraries.
You were actually fine with Configure -d: it installs in /usr/local
with Perl modules in /usr/local/lib/perl5, which is what you want. You
just needed to be root for the 'make install' step.
As a separate issue, it's jolly confusing if you quote your whole
prompt each time. It's usual to just use '$' or '%', or '#' to
indicate a root shell, and to put a space after it, thus:
$ tar -xzvf stable.tar.gz
$ cd perl-5.8.1
$ su
# ./Configure -de
etc.
> make
> ...whole bunch of lines
> libperl.a(pp.o): In function `Perl_pp_pow':
> pp.o(.text+0x1e22): undefined reference to `pow'
> libperl.a(pp.o): In function `Perl_pp_sin':
> pp.o(.text+0x5b08): undefined reference to `sin'
> libperl.a(pp.o): In function `Perl_pp_cos':
> pp.o(.text+0x5c0c): undefined reference to `cos'
> libperl.a(pp.o): In function `Perl_pp_exp':
> pp.o(.text+0x5e0c): undefined reference to `exp'
> libperl.a(pp.o): In function `Perl_pp_log':
> pp.o(.text+0x5f4d): undefined reference to `log'
> libperl.a(pp.o): In function `Perl_pp_sqrt':
> pp.o(.text+0x60a3): undefined reference to `sqrt'
> collect2: ld returned 1 exit status
> make: *** [miniperl] Error 1
> :/home/username/perl-5.8.1#
>
> should I go with
> make test
> make install
>
> what about this Error 1 thing?
That means that 'make' failed. Make failed because ld failed: 'ld
returned 1 exit status'. ld failed because it was trying to find the
definitions for the functions 'pow', 'sin' etc., and couldn't.
The reason it couldn't is because they are in libm.so, which lives in
/lib. It wasn't looking in /lib because you told it to only look in
/usr/local/lib, above.
Right, start over again, and use Configure -de. Become root before you
type 'make install'. When that has finished, issue, as root,
# ln -sf perl5.6.1 /usr/bin/perl
# ln -sf perl5.8.1 /usr/local/bin/perl
# /usr/bin/perl -v
This is perl, v5.6.1 built for i686-linux
<snip>
# /usr/local/bin/perl -v
This is perl, v5.8.1 built for i686-linux
<snip>
If you get different results from that, ask again.
Ben
--
$.=1;*g=sub{print@_};sub r($$\$){my($w,$x,$y)=@_;for(keys%$x){/main/&&next;*p=$
$x{$_};/(\w)::$/&&(r($w.$1,$x.$_,$y),next);$y eq\$p&&&g("$w$_")}};sub t{for(@_)
{$f&&($_||&g(" "));$f=1;r"","::",$_;$_&&&g(chr(0012))}};t # ben@morrow.me.uk
$J::u::s::t, $a::n::o::t::h::e::r, $P::e::r::l, $h::a::c::k::e::r, $.
------------------------------
Date: Tue, 11 Nov 2003 10:31:54 GMT
From: "Mc Kiernan, Daniel Kian" <Mc-Kiernan@bogus-subdomain.worldnet.att.net>
Subject: JVM in perl
Message-Id: <uU2sb.235103$0v4.16960213@bgtnsc04-news.ops.worldnet.att.net>
I'm planning an implementation of the JVM in perl. (I can begin work in
early 2004.) Has anyone else been doing or planning something along these
lines?
------------------------------
Date: Tue, 11 Nov 2003 10:18:28 +0000
From: Helgi Briem <HelgiBriem_1@hotmail.com>
Subject: Re: LWP::UserAgent and SSL is it impossible?
Message-Id: <kpd1rvgplji6vsl9h07ju3h81l06lknmgt@4ax.com>
On Mon, 10 Nov 2003 17:49:02 -0700, Paul Lemmons
<paul@not2bspammed.com> wrote:
>I want to script a login to a secure web site in perl. The web site is
>using session cookies and SSL. It is not using basic authentication. No
>matter what I try I always get "Authentication failed!" returned from
>the server.
Install the Crypt::SSLeay module, then add the line
use Crypt::SSLeay;
to your program.
------------------------------
Date: Tue, 11 Nov 2003 09:18:21 +0100
From: Tore Aursand <tore@aursand.no>
Subject: Re: Perl Newbie
Message-Id: <pan.2003.11.11.07.54.58.950062@aursand.no>
On Mon, 10 Nov 2003 16:01:28 -0800, Harshit K wrote:
> I am sorry if this is a repeated question, maybe I missed it out. I am
> a newbie to perl, so could you suggest some good books on perl.
This is a FAQ;
perldoc -q books
--
Tore Aursand <tore@aursand.no>
------------------------------
Date: Tue, 11 Nov 2003 10:20:45 +0000 (UTC)
From: Andreas Kahari <ak+usenet@freeshell.org>
Subject: Re: Perl Newbie
Message-Id: <slrnbr1dvq.dbc.ak+usenet@vinland.freeshell.org>
In article <Xns9430E81BDA24dkwwashere@216.168.3.30>, David K. Wall wrote:
> Uri Guttman <uri@stemsystems.com> wrote:
[cut]
>> books.perl.org
>
> I didn't know that site existed. It seems like duplication of effort to have
> a list on learn.perl.org and another (larger) one on books.perl.org. Are the
> maintainers of the two sites coordinating their efforts? If not, I think
> they should be....
Why should they? Just because there are more than two sites
about cooking doesn't mean they have to collaborate...
--
Andreas Kähäri
------------------------------
Date: Tue, 11 Nov 2003 02:22:27 -0600
From: tadmc@augustmail.com
Subject: Posting Guidelines for comp.lang.perl.misc ($Revision: 1.4 $)
Message-Id: <bq2dnRM9tozeAS2iRVn-vg@august.net>
Outline
Before posting to comp.lang.perl.misc
Must
- Check the Perl Frequently Asked Questions (FAQ)
- Check the other standard Perl docs (*.pod)
Really Really Should
- Lurk for a while before posting
- Search a Usenet archive
If You Like
- Check Other Resources
Posting to comp.lang.perl.misc
Is there a better place to ask your question?
- Question should be about Perl, not about the application area
How to participate (post) in the clpmisc community
- Carefully choose the contents of your Subject header
- Use an effective followup style
- Speak Perl rather than English, when possible
- Ask perl to help you
- Do not re-type Perl code
- Provide enough information
- Do not provide too much information
- Do not post binaries, HTML, or MIME
Social faux pas to avoid
- Asking a Frequently Asked Question
- Asking a question easily answered by a cursory doc search
- Asking for emailed answers
- Beware of saying "doesn't work"
- Sending a "stealth" Cc copy
Be extra cautious when you get upset
- Count to ten before composing a followup when you are upset
- Count to ten after composing and before posting when you are upset
-----------------------------------------------------------------
Posting Guidelines for comp.lang.perl.misc ($Revision: 1.4 $)
This newsgroup, commonly called clpmisc, is a technical newsgroup
intended to be used for discussion of Perl related issues (except job
postings), whether it be comments or questions.
As you would expect, clpmisc discussions are usually very technical in
nature and there are conventions for conduct in technical newsgroups
going somewhat beyond those in non-technical newsgroups.
This article describes things that you should, and should not, do to
increase your chances of getting an answer to your Perl question. It is
available in POD, HTML and plain text formats at:
http://mail.augustmail.com/~tadmc/clpmisc.shtml
For more information about netiquette in general, see the "Netiquette
Guidelines" at:
http://andrew2.andrew.cmu.edu/rfc/rfc1855.html
A note to newsgroup "regulars":
Do not use these guidelines as a "license to flame" or other
meanness. It is possible that a poster is unaware of things
discussed here. Give them the benefit of the doubt, and just
help them learn how to post, rather than assume
A note about technical terms used here:
In this document, we use words like "must" and "should" as
they're used in technical conversation (such as you will
encounter in this newsgroup). When we say that you *must* do
something, we mean that if you don't do that something, then
it's unlikely that you will benefit much from this group.
We're not bossing you around; we're making the point without
lots of words.
Do *NOT* send email to the maintainer of these guidelines. It will be
discarded unread. The guidelines belong to the newsgroup so all
discussion should appear in the newsgroup. I am just the secretary that
writes down the consensus of the group.
Before posting to comp.lang.perl.misc
Must
This section describes things that you *must* do before posting to
clpmisc, in order to maximize your chances of getting meaningful replies
to your inquiry and to avoid getting flamed for being lazy and trying to
have others do your work.
The perl distribution includes documentation that is copied to your hard
drive when you install perl. Also installed is a program for looking
things up in that (and other) documentation named 'perldoc'.
You should either find out where the docs got installed on your system,
or use perldoc to find them for you. Type "perldoc perldoc" to learn how
to use perldoc itself. Type "perldoc perl" to start reading Perl's
standard documentation.
Check the Perl Frequently Asked Questions (FAQ)
Checking the FAQ before posting is required in Big 8 newsgroups in
general, there is nothing clpmisc-specific about this requirement.
You are expected to do this in nearly all newsgroups.
You can use the "-q" switch with perldoc to do a word search of the
questions in the Perl FAQs.
Check the other standard Perl docs (*.pod)
The perl distribution comes with much more documentation than is
available for most other newsgroups, so in clpmisc you should also
see if you can find an answer in the other (non-FAQ) standard docs
before posting.
It is *not* required, or even expected, that you actually *read* all of
Perl's standard docs, only that you spend a few minutes searching them
before posting.
Try doing a word-search in the standard docs for some words/phrases
taken from your problem statement or from your very carefully worded
"Subject:" header.
Really Really Should
This section describes things that you *really should* do before posting
to clpmisc.
Lurk for a while before posting
This is very important and expected in all newsgroups. Lurking means
to monitor a newsgroup for a period to become familiar with local
customs. Each newsgroup has specific customs and rituals. Knowing
these before you participate will help avoid embarrassing social
situations. Consider yourself to be a foreigner at first!
Search a Usenet archive
There are tens of thousands of Perl programmers. It is very likely
that your question has already been asked (and answered). See if you
can find where it has already been answered.
One such searchable archive is:
http://groups.google.com/advanced_group_search
If You Like
This section describes things that you *can* do before posting to
clpmisc.
Check Other Resources
You may want to check in books or on web sites to see if you can
find the answer to your question.
But you need to consider the source of such information: there are a
lot of very poor Perl books and web sites, and several good ones
too, of course.
Posting to comp.lang.perl.misc
There can be 200 messages in clpmisc in a single day. Nobody is going to
read every article. They must decide somehow which articles they are
going to read, and which they will skip.
Your post is in competition with 199 other posts. You need to "win"
before a person who can help you will even read your question.
These sections describe how you can help keep your article from being
one of the "skipped" ones.
Is there a better place to ask your question?
Question should be about Perl, not about the application area
It can be difficult to separate out where your problem really is,
but you should make a conscious effort to post to the most
applicable newsgroup. That is, after all, where you are the most
likely to find the people who know how to answer your question.
Being able to "partition" a problem is an essential skill for
effectively troubleshooting programming problems. If you don't get
that right, you end up looking for answers in the wrong places.
It should be understood that you may not know that the root of your
problem is not Perl-related (the two most frequent ones are CGI and
Operating System related), so off-topic postings will happen from
time to time. Be gracious when someone helps you find a better place
to ask your question by pointing you to a more applicable newsgroup.
How to participate (post) in the clpmisc community
Carefully choose the contents of your Subject header
You have 40 precious characters of Subject to win out and be one of
the posts that gets read. Don't waste them. Take care while
composing them, they are the key that opens the door to getting an
answer.
Spend them indicating what aspect of Perl others will find if they
should decide to read your article.
Do not spend them indicating "experience level" (guru, newbie...).
Do not spend them pleading (please read, urgent, help!...).
Do not spend them on non-Subjects (Perl question, one-word
Subject...)
For more information on choosing a Subject see "Choosing Good
Subject Lines":
http://www.cpan.org/authors/id/D/DM/DMR/subjects.post
Part of the beauty of newsgroup dynamics, is that you can contribute
to the community with your very first post! If your choice of
Subject leads a fellow Perler to find the thread you are starting,
then even asking a question helps us all.
Use an effective followup style
When composing a followup, quote only enough text to establish the
context for the comments that you will add. Always indicate who
wrote the quoted material. Never quote an entire article. Never
quote a .signature (unless that is what you are commenting on).
Intersperse your comments *following* each section of quoted text to
which they relate. Unappreciated followup styles are referred to as
"Jeopardy" (because the answer comes before the question), or
"TOFU".
Reversing the chronology of the dialog makes it much harder to
understand (some folks won't even read it if written in that style).
For more information on quoting style, see:
http://web.presby.edu/~nnqadmin/nnq/nquote.html
Speak Perl rather than English, when possible
Perl is much more precise than natural language. Saying it in Perl
instead will avoid misunderstanding your question or problem.
Do not say: I have variable with "foo\tbar" in it.
Instead say: I have $var = "foo\tbar", or I have $var = 'foo\tbar',
or I have $var = <DATA> (and show the data line).
Ask perl to help you
You can ask perl itself to help you find common programming mistakes
by doing two things: enable warnings (perldoc warnings) and enable
"strict"ures (perldoc strict).
You should not bother the hundreds/thousands of readers of the
newsgroup without first seeing if a machine can help you find your
problem. It is demeaning to be asked to do the work of a machine. It
will annoy the readers of your article.
You can look up any of the messages that perl might issue to find
out what the message means and how to resolve the potential mistake
(perldoc perldiag). If you would like perl to look them up for you,
you can put "use diagnostics;" near the top of your program.
Do not re-type Perl code
Use copy/paste or your editor's "import" function rather than
attempting to type in your code. If you make a typo you will get
followups about your typos instead of about the question you are
trying to get answered.
Provide enough information
If you do the things in this item, you will have an Extremely Good
chance of getting people to try and help you with your problem!
These features are a really big bonus toward your question winning
out over all of the other posts that you are competing with.
First make a short (less than 20-30 lines) and *complete* program
that illustrates the problem you are having. People should be able
to run your program by copy/pasting the code from your article. (You
will find that doing this step very often reveals your problem
directly. Leading to an answer much more quickly and reliably than
posting to Usenet.)
Describe *precisely* the input to your program. Also provide example
input data for your program. If you need to show file input, use the
__DATA__ token (perldata.pod) to provide the file contents inside of
your Perl program.
Show the output (including the verbatim text of any messages) of
your program.
Describe how you want the output to be different from what you are
getting.
If you have no idea at all of how to code up your situation, be sure
to at least describe the 2 things that you *do* know: input and
desired output.
Do not provide too much information
Do not just post your entire program for debugging. Most especially
do not post someone *else's* entire program.
Do not post binaries, HTML, or MIME
clpmisc is a text only newsgroup. If you have images or binaries
that explain your question, put them in a publically accessible
place (like a Web server) and provide a pointer to that location. If
you include code, cut and paste it directly in the message body.
Don't attach anything to the message. Don't post vcards or HTML.
Many people (and even some Usenet servers) will automatically filter
out such messages. Many people will not be able to easily read your
post. Plain text is something everyone can read.
Social faux pas to avoid
The first two below are symptoms of lots of FAQ asking here in clpmisc.
It happens so often that folks will assume that it is happening yet
again. If you have looked but not found, or found but didn't understand
the docs, say so in your article.
Asking a Frequently Asked Question
It should be understood that you may have missed the applicable FAQ
when you checked, which is not a big deal. But if the Frequently
Asked Question is worded similar to your question, folks will assume
that you did not look at all. Don't become indignant at pointers to
the FAQ, particularly if it solves your problem.
Asking a question easily answered by a cursory doc search
If folks think you have not even tried the obvious step of reading
the docs applicable to your problem, they are likely to become
annoyed.
If you are flamed for not checking when you *did* check, then just
shrug it off (and take the answer that you got).
Asking for emailed answers
Emailed answers benefit one person. Posted answers benefit the
entire community. If folks can take the time to answer your
question, then you can take the time to go get the answer in the
same place where you asked the question.
It is OK to ask for a *copy* of the answer to be emailed, but many
will ignore such requests anyway. If you munge your address, you
should never expect (or ask) to get email in response to a Usenet
post.
Ask the question here, get the answer here (maybe).
Beware of saying "doesn't work"
This is a "red flag" phrase. If you find yourself writing that,
pause and see if you can't describe what is not working without
saying "doesn't work". That is, describe how it is not what you
want.
Sending a "stealth" Cc copy
A "stealth Cc" is when you both email and post a reply without
indicating *in the body* that you are doing so.
Be extra cautious when you get upset
Count to ten before composing a followup when you are upset
This is recommended in all Usenet newsgroups. Here in clpmisc, most
flaming sub-threads are not about any feature of Perl at all! They
are most often for what was seen as a breach of netiquette. If you
have lurked for a bit, then you will know what is expected and won't
make such posts in the first place.
But if you get upset, wait a while before writing your followup. I
recommend waiting at least 30 minutes.
Count to ten after composing and before posting when you are upset
After you have written your followup, wait *another* 30 minutes
before committing yourself by posting it. You cannot take it back
once it has been said.
AUTHOR
Tad McClellan <tadmc@augustmail.com> and many others on the
comp.lang.perl.misc newsgroup.
------------------------------
Date: Tue, 11 Nov 2003 09:18:22 +0100
From: Tore Aursand <tore@aursand.no>
Subject: Re: simplify this if loop
Message-Id: <pan.2003.11.11.07.46.25.390031@aursand.no>
On Mon, 10 Nov 2003 21:31:36 +0000, John W. Krahn wrote:
> my $m = 2;
> sub avg { my $tot; $tot += $_ for @_; $tot / @_ }
> for ( my $i = $m - 1; my @group = @data[ $i - ( $m - 1 ) .. $i ], $i < @data; ++$i ) {
> print $i + 1, " ", $group[ -1 ], " ", avg( @group ), "\n";
> }
Damn. It's fast, too! :-) Seems like it's 26% faster than "my" method,
which in turn was 34% faster than the OP's method.
Nice!
--
Tore Aursand <tore@aursand.no>
------------------------------
Date: 11 Nov 2003 08:22:05 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@rwth-aachen.de>
Subject: Re: Sort array of objects using a method
Message-Id: <boq67d$1md$1@nets3.rz.RWTH-Aachen.DE>
Also sprach Uri Guttman:
>>>>>> "M" == Marcus <bayrazone@web.de> writes:
>
> M> Hello, I'am a newbee in Perl and in Newsgroups. But I hope for some
> M> help.
>
> M> I have a array of Objekts and i want to sort these Objekts by using a
> M> Objektmethod.
>
> M> I tried this:
> M> certainly the Objektstore ist filled with Objekts !!!
>
> M> @unsortedObjektstore
>
> M> @sortedObjekts = sort {$unsortedObjektstore->getNumber() <=>
> M> $unsortedObjektstore->getNumber()} @unsortedObjektstore;
>
> where did $unsortedObjektstore get its value? sort doesn't put it there.
>
> M> I thougt it works like an example in perldoc:
> M> # sort numerically descending
> M> @articles = sort {$b <=> $a} @files;
>
> so do the same as sort. note that $a and $b are special variable that
> sort uses to assign pairs of values to be compared. your code assumed
> your own variable name which is wrong.
>
> so use use $a and $b as the objects and call your methods like you did:
>
> @sortedObjekts = sort { $a->getNumber() <=> $b->getNumber()}
> @unsortedObjektstore;
A good moment to also mention one of the transforms as I wouldn't want
to call two methods n*log(n) times. Schwartzian transform comes to mind
(hmmh, Guttman-Rosler can't be used on objects, can it?):
@sortedObjects = map { $_->[1] }
sort { $a->[0] <=> $b->[0] }
map { [ $_->getNumber, $_ ] } @sortedObjects;
Tassilo
--
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval
------------------------------
Date: 11 Nov 2003 08:12:50 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@rwth-aachen.de>
Subject: Re: Style question: map versus foreach
Message-Id: <boq5m2$rc$1@nets3.rz.RWTH-Aachen.DE>
Also sprach Darin McBride:
> Abigail wrote:
>
>> Darin McBride (dmcbride@naboo.to.org.no.spam.for.me) wrote on MMMDCCXXIII
>> September MCMXCIII in <URL:news:FRCrb.356754$pl3.261426@pd7tw3no>:
>> __ Abigail wrote:
>> __
>> __ No, you're right. I suppose you overlooked the "that's the concept"
>> __ part of that paragraph. Context rules in perl. But that doesn't mean
>> __ that context rules in the maintainer's head when trying to decipher
>> __ what was written.
>>
>> If you're going to assume the maintainer doesn't know basic concepts
>> of Perl, all bets are off. Then one might want to avoid hashes and
>> regexes too.
[...]
> The main point of map is the return value. The main point of foreach
> is the iteration over an array (no return value implied).
>
> o Avoid using grep() (or map()) or `backticks` in a void
> context, that is, when you just throw away their
> return values. Those functions all have return val-
> ues, so use them. Otherwise use a foreach() loop or
> the system() function instead.
>
> I think this is the whole debate. Unfortunately, there's no real
> explicit justification here.
The mentioning of map() needs to be scratched from perlstyle.pod as it's
no longer true. Forgot to include that in my map-patch.
>> Of course, map already had to check context. It wasn't that map left
>> its intermediar list on the stack if it was called in void or scalar
>> context.
>
> It's just an extra check. I'm sure it was something like (simplified
> for CODE case only):
>
> sub map {
> my $code = shift;
> my @r;
> foreach (@_) {
> my @a = $code->();
> if (wantarray) {
> push @r, @a;
> }
> else {
> $r[0] += scalar @a;
> }
> }
> wantarray ? @r : $r[0];
> }
>
> Now it's more like:
>
> sub map {
> my $code = shift;
> my @r;
> foreach (@_) {
> my @a = $code->();
> if (defined wantarray) {
> if (wantarray) {
> push @r, @a;
> }
> else {
> $r[0] += scalar @a;
> }
> }
> }
> wantarray ? @r : $r[0];
> }
>
> That's just an extra level of checks that isn't needed. Of course,
> there are other ways to write this - some simpler, others faster. And,
> of course, it's probably all in native (C) code anyway. Probably using
> a case statement - which has its own overhead.
Much easier. This
if (items) {
had to become
if (items && gimme != G_VOID) {
If the condition evaluates to false, about 15 lines of code are skipped
and pp_mapwhile (the core of a map() statement) becomes quite a simple
operation.
Which however doesn't change the fact that foreach is faster. The
difference is marginal for 'map EXPR, LIST' (6% in favour of for).
Strangely enough, map is disproportionally slower in the 'map BLOCK
LIST' case...around 50%.
>> __ I suppose you also missed pretty much any of my post that you didn't
>> __ quote. My point, as opposed to others, is that even without the speed
>> __ penalty, there is a stylistic benefit to using foreach when you may
>> __ otherwise wish to use map in void context.
>> __
>> __ It's simply more *obvious* to use map for array contexts and foreach
>> in
>> __ void contexts. And that, regardless of any speed difference, is
>> enough
>> __ reason to discourage map in void context.
>>
>> "Obvious" is something subjective. *YOU* might find one way of doing
>> something more obvious than doing it another way. But that doesn't
>> mean it's true for everyone. Could you please explain why you find
>> map in void context so non-obvious? Do you think map in general is
>> non-obvious, or do you only get confused when the context is void?
>> What about other functions in void context? Are they non-obvious too?
>> Or is it only map that's non-obvious?
>
> Given that map and foreach do almost exactly the same thing with only
> the desired contexts being different, it makes sense to me that one
> would use the version one desires based on that context difference.
> Thus, when I see map in void context, the first thought in my mind is
> "they didn't get the return from map!". Then, after scrutinising the
> map's block (as it's usually a block not an expression), I may figure
> out that they intended to have void (e.g., only doing it for the side
> effect). And then, if that's not the source of the problem, I can go
> on.
There's also a different syntax involved:
map BLOCK LIST
map EXPR, LIST
versus
for LIST BLOCK
STATEMENT for LIST
Particularly, you can change from EXPR to BLOCK without changing a lot
in your code when using map().
>> Is there anyone who can explain why map in void context is confusing,
>> but other functions aren't?
>
> Simply have your code say what you mean rather than trick the virtual
> machine into doing what you want by side effect. In general, side
> effects make code harder to understand.
Depends on the standpoint. When I began with Perl, the return value of
map() was the side-effect (side-effect in the way that I didn't use this
feature). I was familiar with the idea of mapping a function to members
of a list however. That was before I learned about statement-modifiers
therefore using map() in void context was the natural choice for me (it
no longer is to this extent since these statement-modifiers somewhat
changed my habits).
Anyway, you can't make assumptions about how a programmer thinks. Or at
least you can't expect to always make the right ones.
Tassilo
--
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval
------------------------------
Date: Tue, 11 Nov 2003 08:52:48 +0000 (UTC)
From: Ben Morrow <usenet@morrow.me.uk>
Subject: Re: Style question: map versus foreach
Message-Id: <boq810$6pl$2@wisteria.csv.warwick.ac.uk>
tassilo.parseval@post.rwth-aachen.de wrote:
> Strangely enough, map is disproportionally slower in the 'map BLOCK
> LIST' case...around 50%.
Presumably this is the overhead involved in setting up and tearing
down a BLOCK?
Ben
--
Musica Dei donum optimi, trahit homines, trahit deos. |
Musica truces molit animos, tristesque mentes erigit. | ben@morrow.me.uk
Musica vel ipsas arbores et horridas movet feras. |
------------------------------
Date: 11 Nov 2003 09:09:54 GMT
From: "Tassilo v. Parseval" <tassilo.parseval@rwth-aachen.de>
Subject: Re: Style question: map versus foreach
Message-Id: <boq912$4b7$1@nets3.rz.RWTH-Aachen.DE>
Also sprach Ben Morrow:
> tassilo.parseval@post.rwth-aachen.de wrote:
>> Strangely enough, map is disproportionally slower in the 'map BLOCK
>> LIST' case...around 50%.
>
> Presumably this is the overhead involved in setting up and tearing
> down a BLOCK?
Yes, most certainly. But I would expect a similar overhead when using
blocks and foreach. Maybe it has something to do with the callback
nature of BLOCK in the map() case. Afterall, map() is a function while
foreach is not.
Tassilo
--
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval
------------------------------
Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Digest Administrivia (Last modified: 6 Apr 01)
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.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.
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 V10 Issue 5779
***************************************