[30987] in Perl-Users-Digest
Perl-Users Digest, Issue: 2232 Volume: 11
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Feb 24 14:09:40 2009
Date: Tue, 24 Feb 2009 11:09: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, 24 Feb 2009 Volume: 11 Number: 2232
Today's topics:
[DGBI] It depends (was: Sorting hash of hashes) <whynot@pozharski.name>
Re: debugging on stdout <ben@morrow.me.uk>
Posting Guidelines for comp.lang.perl.misc ($Revision: tadmc@seesig.invalid
Strange behavior with MIME::Lite <edMbj@aes-intl.com>
Re: Trying to convert small C++ subroutine (by Peter We <smallpond@juno.com>
Re: Trying to convert small C++ subroutine (by Peter We (Jens Thoms Toerring)
Re: Trying to convert small C++ subroutine (by Peter We sln@netherlands.com
Re: Trying to convert small C++ subroutine (by Peter We sln@netherlands.com
Re: Trying to convert small C++ subroutine (by Peter We <uri@stemsystems.com>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Tue, 24 Feb 2009 11:09:19 +0200
From: Eric Pozharski <whynot@pozharski.name>
Subject: [DGBI] It depends (was: Sorting hash of hashes)
Message-Id: <slrngq7ebv.t1h.whynot@orphan.zombinet>
On 2009-02-23, Greg Bacon <gbacon@hiwaay.net> wrote:
*SKIP*
> Note that /[P|p]erl/ matches "Perl", "perl", and "|erl". You've
> conflated /[Pp]erl/ and /(P|p)erl/. Prefer the former pattern:
> the latter, although equivalent, looks odd. (There's also a small
> performance penalty.)
In *this* case, that matters only in case string matches. Otherwise
they can't decide who would be faster (string C<erl> is anchored at
point 1, then if there's no such string in a pattern the whole match
fails). OTOH, I wouldn't call B<TRIE-EXACT> being *2* times slower a
'small performance penalty'.
perl -wle '
use Benchmark qw|cmpthese timethese|;
my $x = q|Perl|;
my $y = q|PERL|;
cmpthese timethese -10, {
alt_p => sub { $x =~ m{(?:P|p)erl} },
alt_n => sub { $y =~ m{(?:P|p)erl} },
cls_p => sub { $x =~ m{[Pp]erl} },
cls_n => sub { $y =~ m{[Pp]erl} },
};
'
Benchmark:
running
alt_n, alt_p, cls_n, cls_p
for at least 10 CPU seconds
...
alt_n: 12 wallclock secs (11.27 usr + -0.19 sys = 11.08 CPU) @
1174967.24/s (n=13018637)
alt_p: 11 wallclock secs (10.02 usr + 0.01 sys = 10.03 CPU) @
252231.51/s (n=2529882)
cls_n: 12 wallclock secs (11.83 usr + 0.16 sys = 11.99 CPU) @
1114404.34/s (n=13361708)
cls_p: 12 wallclock secs (10.46 usr + 0.05 sys = 10.51 CPU) @
503643.10/s (n=5293289)
Rate alt_p cls_p cls_n alt_n
alt_p 252232/s -- -50% -77% -79%
cls_p 503643/s 100% -- -55% -57%
cls_n 1114404/s 342% 121% -- -5%
alt_n 1174967/s 366% 133% 5% --
--
Torvalds' goal for Linux is very simple: World Domination
Stallman's goal for GNU is even simpler: Freedom
------------------------------
Date: Tue, 24 Feb 2009 09:28:23 +0000
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: debugging on stdout
Message-Id: <n6rc76-1ok.ln1@osiris.mauzo.dyndns.org>
Quoth mike <no_th@nks.org>:
>
> I have a perl script which talks to mplayer and stepping through it in
> emacs' cperl-db it executes flawlessly; but running "./script video" it
> does everything except one crucial step and I'm having a hard time
> visualizing what could be the matter.
>
> so is there a way to invoke the perl script such as can be done in bash or
> csh (csh -xvf ./script.csh) which would allow me to see what's going on at
> full speed?
See perldoc perldebug.
Ben
------------------------------
Date: Tue, 24 Feb 2009 08:17:08 GMT
From: tadmc@seesig.invalid
Subject: Posting Guidelines for comp.lang.perl.misc ($Revision: 1.9 $)
Message-Id: <82Ool.14486$as4.11189@nlpi069.nbdc.sbc.com>
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.9 $)
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.
The article at:
http://www.catb.org/~esr/faqs/smart-questions.html
describes how to get answers from technical people in general.
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://www.rehabitation.com/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 that they do
know and are being the "bad kind" of Lazy.
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_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
"top-posting", "Jeopardy" (because the answer comes before the
question), or "TOFU" (Text Over, Fullquote Under).
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 and many others on the comp.lang.perl.misc newsgroup.
--
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"
------------------------------
Date: Tue, 24 Feb 2009 10:44:36 -0800
From: Ed Jay <edMbj@aes-intl.com>
Subject: Strange behavior with MIME::Lite
Message-Id: <o8f8q4tes64n0e7b8i8jgfedc6h2ltugar@4ax.com>
I have an html file residing on my server that I want to attach as an
email attachment. I'm using MIME::Lite as follows:
use MIME::Lite;
use Net::SMTP;
$info_email = "info\@myDomain\.com";
$date2 = '022109';
my $mail_host = 'mail.myDomain.com';
$reportPath = "/home/wwwbrea/public_html/reports/";
$email = 'ed@edsDomain.com';
$subject = 'Information You Requested';
# Create container
$msg = MIME::Lite->new (
From => $info_email,
To => $email,
Subject => $subject,
Type =>'multipart/mixed'
) or die "Error creating multipart container: $!\n";
### email body text message
$msg->attach (
Type => 'TEXT',
Data => $message_body
) or die "Error adding the text message part: $!\n";
### Add attachment
$ptReportFile = 'TestProcess4'.$date2.'.html';
$my_file_path = './'.$ptReportFile;
$msg->attach (
Type => 'text/html',
Path => $my_file_path,
Filename => $ptReportFile,
Disposition => 'attachment'
) or die "Error adding $ptReport: $!\n";
MIME::Lite->send('smtp', $mail_host, Timeout=>60);
$msg->send;
In the 'add attachment' section, if the mime type is text/html or
txt/plain, this script doesn't send. But, if I change the mime type to
'application/pdf' or any other 'application/XX,' including a fake mime
type as 'application/html,' the script works. WTF???
--
Ed Jay (remove 'M' to reply by email)
Win the War Against Breast Cancer.
Knowing the facts could save your life.
http://www.breastthermography.info
------------------------------
Date: Tue, 24 Feb 2009 09:18:51 -0800 (PST)
From: smallpond <smallpond@juno.com>
Subject: Re: Trying to convert small C++ subroutine (by Peter Weinberger) to Perl
Message-Id: <d79e2ebb-b660-4f28-aa34-e69a5a6047c0@j12g2000vbl.googlegroups.com>
On Feb 24, 1:36 am, David Filmer <use...@DavidFilmer.com> wrote:
> #!/usr/bin/perl
> use strict;
>
> print hashpjw( 'bar', 123 );
Call hashpjw with two args, a string 'bar' and a number 123
>
> sub hashpjw {
> my( $char, $s ) = @_;
Get two args: $char = 'bar' and $s = 123
> for my $char( $p = $s, $p, $p++ ) {
Here you define a new $char hiding the one that has 'bar'.
Also this loop is almost certainly not doing what you want, unless
what you want is very strange:
perl -e 'for $c ($p=123, $p, $p++) { print $c,"\n" }'
124
124
123
> Any assistance is greatly appreciated!
Start by treating perl as a different language than C. First off,
there are no pointers, so trying to do pointer arithmetic is, well,
pointless.
------------------------------
Date: 24 Feb 2009 09:11:20 GMT
From: jt@toerring.de (Jens Thoms Toerring)
Subject: Re: Trying to convert small C++ subroutine (by Peter Weinberger) to Perl
Message-Id: <70hrtoF7cokfU1@mid.uni-berlin.de>
David Filmer <usenet@davidfilmer.com> wrote:
> In the book, "Programming in C++" by Stephen Dewhurst and Kathy Stark
> (1989, Prentice Hall, page 14), I find a short hashing subroutine
> ("hash" as in cryptographic hash, not an associative array) by the
> famous Peter Weinberger.
> The subroutine accepts a string, and returns a numerical value. One
> possible application of such a subroutine would be for storing (and
> retrieving) of a vast number of files (many thousands or millions) -
> the files could be stored in an arbitrary number of directories/
> filesystems (ie, "hash buckets") and retrieved based on the hash value
> of their filename.
Mmmm, but you also have to take into account possible "hash
collisions"...
> I wish to convert this C++ subroutine to a Perl subroutine. But my
> knowledge of C++ is limited to what I learned in a class in college -
> I have never coded in C++ and I am severely deficient in this
> language.
> Based on my limited C++ skills, I have made an effort to do this
> conversion, but it does not produce the expected results. I was
> hoping someone here who was more familiar with C++ could point out the
> error of my ways.
> Here is subroutine from the book, based on Peter Weinberger's code:
> int
> hashpjw( char *s ) {
> const prime = 211;
> unsigned hash = 0, g;
> for( char *p = s; *p, p++ ) {
> hash = ( hash << 4 ) + *p;
> // assumes 32 bit int size
> if( g = hash & 0xf0000000 ) {
> hash ^= g >> 24;
> hsh ^= g;
> }
> }
> return hash % prime;
> }
Your 'prime' is awfully small, with that you never get more
than 211 different hash values...
> Here is my <lame>attempt</lame> to convert it to Perl:
> #!/usr/bin/perl
> use strict;
use warnings;
;-)
> print hashpjw( 'bar', 123 );
Why do you pass it two arguments if the C/C++ version only
takes a single one, the string of which you want to compute
the hash value?
> sub hashpjw {
> my( $char, $s ) = @_;
> my $prime = 211;
> my ( $hash, $g, $p );
> for my $char( $p = $s, $p, $p++ ) {
> $hash = ( $hash << 4 ) + $p;
> if( $g = $hash & 0xf0000000 ) {
> $hash = $hash ^ ($g >> 24);
> $hash = $hash ^ $g;
> }
> }
> return $hash % $prime;
> }
Try this instead (and pass it just the string)
sub hashpjw {
my ( $s, $prime, $hash ) = ( shift, 211, 0 );
for ( split //, $s ) {
$hash = ( $hash << 4 ) + ord $_;
if ( my $g = $hash & 0xf0000000 ) {
$hash ^= $g >> 24;
$hash ^= $g;
}
}
return $hash % $prime;
}
One warning: the C/C++ version is rather likely meant to be used
with 8-bit characters. The Perl version as it is will happily
accept e.g. Unicode characters and then the result will differ
from the C/C++ version!
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
------------------------------
Date: Tue, 24 Feb 2009 18:24:46 GMT
From: sln@netherlands.com
Subject: Re: Trying to convert small C++ subroutine (by Peter Weinberger) to Perl
Message-Id: <ege8q41u2bbnvhk089c002bmpqogujm86f@4ax.com>
On 24 Feb 2009 09:11:20 GMT, jt@toerring.de (Jens Thoms Toerring) wrote:
>David Filmer <usenet@davidfilmer.com> wrote:
>> In the book, "Programming in C++" by Stephen Dewhurst and Kathy Stark
>> (1989, Prentice Hall, page 14), I find a short hashing subroutine
[snip]
>Try this instead (and pass it just the string)
>
>sub hashpjw {
> my ( $s, $prime, $hash ) = ( shift, 211, 0 );
>
> for ( split //, $s ) {
> $hash = ( $hash << 4 ) + ord $_;
> if ( my $g = $hash & 0xf0000000 ) {
> $hash ^= $g >> 24;
> $hash ^= $g;
> }
> }
>
> return $hash % $prime;
>}
>
The oputput for this is the same as the C function, for
'bar' its 168. However the C function as typed in won't compile
without some fixes.
If there were ever a need for speed, the last two $hash asignments
can be combined into a single asignment.
$hash = ($hash ^ $g >> 24) ^ $g;
-sln
------------------------------
Date: Tue, 24 Feb 2009 18:32:30 GMT
From: sln@netherlands.com
Subject: Re: Trying to convert small C++ subroutine (by Peter Weinberger) to Perl
Message-Id: <jre8q4dlcc8o35k61ug49l56854ngqafun@4ax.com>
On Mon, 23 Feb 2009 22:36:22 -0800 (PST), David Filmer <usenet@DavidFilmer.com> wrote:
>Greetings.
>
>In the book, "Programming in C++" by Stephen Dewhurst and Kathy Stark
>(1989, Prentice Hall, page 14), I find a short hashing subroutine
>("hash" as in cryptographic hash, not an associative array) by the
>famous Peter Weinberger.
>
>The subroutine accepts a string, and returns a numerical value. One
>possible application of such a subroutine would be for storing (and
>retrieving) of a vast number of files (many thousands or millions) -
>the files could be stored in an arbitrary number of directories/
>filesystems (ie, "hash buckets") and retrieved based on the hash value
>of their filename.
>
>I wish to convert this C++ subroutine to a Perl subroutine. But my
>knowledge of C++ is limited to what I learned in a class in college -
>I have never coded in C++ and I am severely deficient in this
>language.
>
>Based on my limited C++ skills, I have made an effort to do this
>conversion, but it does not produce the expected results. I was
>hoping someone here who was more familiar with C++ could point out the
>error of my ways.
>
>Here is subroutine from the book, based on Peter Weinberger's code:
>
>int
>hashpjw( char *s ) {
> const prime = 211;
> unsigned hash = 0, g;
>
> for( char *p = s; *p, p++ ) {
> hash = ( hash << 4 ) + *p;
> // assumes 32 bit int size
> if( g = hash & 0xf0000000 ) {
> hash ^= g >> 24;
> hsh ^= g;
> }
> }
> return hash % prime;
>}
>
[snip]
Jen has a nice Perl solution.
But, the C code won't compile under C++, probably some typo's.
C++ does not support default-int
There is no default type for const.
The for loop has a ',' where it should have a ';'.
Fixed up and speedier version:
int
hashpjw( char *s ) {
const int prime = 211;
unsigned hash = 0, g;
for( char *p = s; *p; p++ ) {
hash = ( hash << 4 ) + *p;
// assumes 32 bit int size
if( g = hash & 0xf0000000 )
hash = (hash ^ g >> 24) ^ g;
}
return hash % prime;
}
-sln
------------------------------
Date: Tue, 24 Feb 2009 12:30:01 -0500
From: Uri Guttman <uri@stemsystems.com>
Subject: Re: Trying to convert small C++ subroutine (by Peter Weinberger) to Perl
Message-Id: <x71vtng2ue.fsf@mail.sysarch.com>
>>>>> "DF" == David Filmer <usenet@DavidFilmer.com> writes:
hi dave!
DF> In the book, "Programming in C++" by Stephen Dewhurst and Kathy Stark
DF> (1989, Prentice Hall, page 14), I find a short hashing subroutine
DF> ("hash" as in cryptographic hash, not an associative array) by the
DF> famous Peter Weinberger.
well, perl hashes are called that because they use a hash function to
allow O(1) (or close to it) access!
DF> The subroutine accepts a string, and returns a numerical value. One
DF> possible application of such a subroutine would be for storing (and
DF> retrieving) of a vast number of files (many thousands or millions) -
DF> the files could be stored in an arbitrary number of directories/
DF> filesystems (ie, "hash buckets") and retrieved based on the hash value
DF> of their filename.
which is also how perl hashes work!
DF> int
DF> hashpjw( char *s ) {
DF> const prime = 211;
DF> unsigned hash = 0, g;
DF> for( char *p = s; *p, p++ ) {
DF> hash = ( hash << 4 ) + *p;
DF> // assumes 32 bit int size
DF> if( g = hash & 0xf0000000 ) {
DF> hash ^= g >> 24;
DF> hsh ^= g;
DF> }
DF> }
DF> return hash % prime;
DF> }
DF> print hashpjw( 'bar', 123 );
you pass a string to $char but a number to $s
DF> sub hashpjw {
DF> my( $char, $s ) = @_;
the c++ code declares only a single char pointer arg which is similar to
a perl string. and as i pointed out above, you pass in two args.
DF> my $prime = 211;
DF> my ( $hash, $g, $p );
DF> for my $char( $p = $s, $p, $p++ ) {
that redeclares $char so the string arg you pass in is never used. also
this loop just scans the string to be hashed. there are many easy idioms
for this. this s about the simplest but may be slow on very long
strings:
foreach my $char ( split //, $s ) {
this works better on long strings:
while( my ($char) = $s =~ /(.)/sg ) {
DF> $hash = ( $hash << 4 ) + $p;
you never set $p to anything. it needs to be the next char. so change $p
to $char. *p is accessing the next char in the c++ string.
DF> if( $g = $hash & 0xf0000000 ) {
DF> $hash = $hash ^ ($g >> 24);
DF> $hash = $hash ^ $g;
DF> }
that looks ok but i can't tell without testing.
DF> }
DF> return $hash % $prime;
same here.
well, you never scan the input string which is never properly passed
in. fix those bugs and see what happens. also test this out with a
single char string so you can debug all the steps more easily.
uri
--
Uri Guttman ------ uri@stemsystems.com -------- http://www.sysarch.com --
----- Perl Code Review , Architecture, Development, Training, Support ------
--------- Free Perl Training --- http://perlhunter.com/college.html ---------
--------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com ---------
------------------------------
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.
NOTE: due to the current flood of worm email banging on ruby, the smtp
server on ruby has been shut off until further notice.
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 V11 Issue 2232
***************************************