[17948] in Perl-Users-Digest
Perl-Users Digest, Issue: 108 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sat Jan 20 21:05:43 2001
Date: Sat, 20 Jan 2001 18:05:09 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <980042708-v10-i108@ruby.oce.orst.edu>
Content-Type: text
Perl-Users Digest Sat, 20 Jan 2001 Volume: 10 Number: 108
Today's topics:
Re: Counting elements in an array (foreach) <Juha.Laiho@iki.fi>
Expect module and SSH <nathanf@gurunet.com>
Re: GD.pm/ImageMagick - Any thing better? (Martien Verbruggen)
Re: help needed with parsing a HTML form nobull@mail.com
Re: help needed with parsing a HTML form (Eric Bohlman)
matching "*"? <j_graumann@hotmail.com>
Re: matching "*"? (Mike Stok)
Re: matching "*"? (Martien Verbruggen)
Re: matching "*"? <godzilla@stomp.stomp.tokyo>
Re: Multiprocess or multithreaded??? (Martien Verbruggen)
Newbie question - deleting directories <ewsr1@home.com>
Re: Newbie question nobull@mail.com
Re: percentages, how? <kstep@pepsdesign.com>
Re: percentages, how? (Abigail)
Re: percentages, how? <godzilla@stomp.stomp.tokyo>
Perl Crashes on my Win2k Box <hogan@go away.com>
Perl in C <ediril@ece.wpi.edu>
Perl in C <ediril@ece.wpi.edu>
Re: Powerful Technique 3606 (Abigail)
Re: Powerful Technique 3606 (Martien Verbruggen)
Question re: Mail::Internet (Ranyart Olias)
Re: redirect and cookie (+domain) does not work! nobull@mail.com
Re: Spawning Parallel Processes (Martien Verbruggen)
Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: 20 Jan 2001 11:53:56 +0200
From: Juha Laiho <Juha.Laiho@iki.fi>
Subject: Re: Counting elements in an array (foreach)
Message-Id: <94bn7k$ako$1@ichaos.ichaos-int>
"Jerry Pank" <me@jp1.co.uk> said:
>If I wish to count elements whilst looping through an array, I resort to $i
>as below.
>I would have thought perl would have had a `special' variable for this.
>There probably is but I can't find one in my reference material.
>
>#!bin/perl5 -w
>
>use strict;
>my @array=(1..100);
>my $i;
>foreach my $element(@array) {
> $i++;
> # do stuff
> print "Done element $i\n";
>}
Depends on what you're doing -- you could use the $element directly,
or avoid even the $element and use $_.
Also, there's $#array that returns the highest index in the array,
and evaluating @array itself in the scalar context will return the
number of elements in the array.
--
Wolf a.k.a. Juha Laiho Espoo, Finland
(GC 3.0) GIT d- s+: a- C++ UH++++$ UL++++ P+@ L+++ E(-) W+$@ N++ !K w !O
!M V PS(+) PE Y+ PGP(+) t- 5? !X R tv--- b+ DI? D G e+ h--- r+++ y+
"...cancel my subscription to the resurrection!" (Jim Morrison)
------------------------------
Date: Sat, 20 Jan 2001 04:16:11 +0200
From: Nathan Fain <nathanf@gurunet.com>
Subject: Expect module and SSH
Message-Id: <3A68F4EA.1480842D@gurunet.com>
I'm trying to create a script to act as a shell to ssh allowing me to
open multiple ssh sessions with one input from the user. That is,
taking a
command(s) from the user and executing it on 3 different machines. This
is possible with Net::Telnet and I'm trying to do the same using
Expect and SSH. The ssh module (forgot the tree) doesn't allow me to
create ssh objects sufficient to do what I want. Below is the code I'm
using. I believe the problem has to do with opening multiple objects
using the Expect module.
Guide me oh wise ones (willing to RTFM):
#!/usr/bin/perl -w
use strict;
use Expect;
my %servers = (
test => ['SERVER1', 'SERVER2'],
);
my ($username, $password) = ('user', 'password');
my $server = shift @ARGV;
if ($server =~ /^-[h?]/) {
print "Usage: navssh [lu|web|ftp|db]\n";
exit;
}
$servers{$server} or die "Unknown server: $server\n";
my @connects;
foreach (0 .. $#{$servers{$server}}) {
($connects[$_] = Expect->spawn("ssh
$username\@$servers{$server}->[$_]")) || die "Couldn't spawn ssh\n";
my $conn = $connects[$_];
if ($conn->expect(20,"$username\'s password: ")) {
print $conn "$password\r";
} else {
die "Never got username prompt on
$servers{$server}->[$_], ".$connects[$_]->exp_error
()."\n";
}
}
# Interestingly enough, if I comment out the following code and reduce
the servers to 1 then it actually works.
$| = 1;
while (<>) {
chomp;
my $cmd = $_;
foreach (@connects) {
print $_ "$cmd\r";
}
$| = 1;
}
# yeah, need to changs this to something else from the Net::Telnet
close... later:
foreach (@connects) {
$_->hard_close();
}
------------------------------
Date: Sun, 21 Jan 2001 10:31:21 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: GD.pm/ImageMagick - Any thing better?
Message-Id: <slrn96k7u9.bgr.mgjv@martien.heliotrope.home>
On Sat, 20 Jan 2001 21:00:16 GMT,
Sterling <smullett@omeninc.com> wrote:
> H-
>
> Thanks for your reply.
>
>> > I had looked into using Magick but it really doesn't do all the drawing
>> > things that I'll need.
>>
>> That surprises me a bit. What sort of drawign are you able to do with GD
>> that you can't do with Image::Magick? I tend to believe that
>> Image::Magick has a lot more than GD. GD is just faster.
>
> Well to be fair I did find the draw feature. The problem I've been
> encountering is that it only works when loading images and doing stuff
> to those images. I want to create the images from scratch. So far that
> hasn't worked out.
> Meaning either I'm doing something wrong (most likely) or magick doesn't
> like to work/create images from scratch.
All you need to do is use Read() to create a blank image with one of the
builtin image types. Here's an example, showing some of the drawing
primitives:
use Image::Magick;
# Create a new image
my $im = Image::Magick->new(size => '400x300');
# Give it a white background
$im->Read('xc:white');
# Set the default drawing color
$im->Set(stroke => 'red');
# Put a rectangle in there somewhere
$im->Draw(primitive => 'rectangle',
points => '0,129 199,169',
fill => 'blue',
stroke => 'blue');
# Create a polygon with a few vertices
$im->Draw(primitive => 'polygon',
points => '199,149 399,74 324,149 399,224',
fill => 'yellow',
stroke => 'black');
$im->Set(antialias => 0, fuzz => 15);
# Draw a circle around the middle of the image,
# with a diameter of 250 pixels
$im->Draw(primitive => 'circle',
linewidth => 3,
points => '199,149 74,149');
# Cut out an ellipse shape
$im->Draw(primitive => 'ellipse',
linewidth => 3,
points => '199,149 50,100 0,360');
# And fill the space between with green
$im->Draw(primitive => 'color',
method => 'filltoborder',
points => '99,149',
bordercolor => 'red',
fill => 'green1');
# Frame the whole thing with a red border, and
# put a red cross on it
$im->Draw(primitive => 'rectangle',
points => '0,0 399,299');
$im->Draw(primitive => 'line',
points => '199,0 199,299');
$im->Draw(primitive => 'line',
points => '0,149 399,149');
$im->Write('IMExample.png');
There are other primitives that do much cooler things. If you want to
have more documentation on Image::magick than the Perl interface doc
gives you, read the documentation on the command line tools convert,
combine and mogrify. Most arguments for those tools have equivalents in
the Perl API.
Oh, the 'xc' in the above is one of the builtin IM types (for X color).
> For now I'm attempting to do a simple image create(using Image::Magick).
> But perhaps this should be taken to some other newsgroup.
> Do you know of any?
The best place to discuss Image::Magick is the mailing list. You can
find information about it on www.imagemagick.org. There is also an
archive of older messages around somewhere. It probably has a link to
those as well.
>> Oh, I'm forgetting one: You can use the interface to the Gimp. But
>> prepare for a steep learning curve, and long searches through
>> documentation. if you're not already fluent with the Gimp itself, it's
>> hardly useful to even lok at the programmable Perl interface.
>
> Yes, I saw the Gimp interface and was tempted to get into it. Haven't
> had good working relations with GIMP. Just me though.
The main difficulty with the Gimp Perl interface is that you need to
know so many things before it becomes really useable. A lot to learn and
a lot to read. If you have the time to do that, there still is one
problm left: The Gimp in general isn't a drawing package, even though
you can use it to do that. It's really an image manipulation program.
I'd give Image::Magick a bit more of a try.
Martien
--
Martien Verbruggen |
Interactive Media Division | Think of the average person. Half of
Commercial Dynamics Pty. Ltd. | the people out there are dumber.
NSW, Australia |
------------------------------
Date: 20 Jan 2001 23:08:42 +0000
From: nobull@mail.com
Subject: Re: help needed with parsing a HTML form
Message-Id: <u97l3p3jph.fsf@wcl-l.bham.ac.uk>
"whitetigercat" <whitetiger@pinc.com> writes:
> I am writing a program to retrieve a html page containing a form
> from another site. I am using LWP::Simple for this and it works
> great at getting and storing the page. Now I need to extract the
> field names and default values from a form on that page and store
> them in an associative array. I haven't done this part of the
> program yet but if anyone knows a quick script to do this, it would
> be appreciated.
Have you tried looking on CPAN. ISTR seeing a module that claims it
does just that. I think it had a really obsure name like maybe
something with "HTML" and "form" in it.
> Also, how do I do the post (is there a module I should use)?
Check out the rest of what LWP has to offer.
--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
------------------------------
Date: 20 Jan 2001 23:33:04 GMT
From: ebohlman@omsdev.com (Eric Bohlman)
Subject: Re: help needed with parsing a HTML form
Message-Id: <94d77g$5lk$1@bob.news.rcn.net>
whitetigercat <whitetiger@pinc.com> wrote:
> I am writing a program to retrieve a html page containing a form from another site.
> I am using LWP::Simple for this and it works great at getting and storing the page.
> Now I need to extract the field names and default values from a form on that page
> and store them in an associative array. I haven't done this part of the program yet but
> if anyone knows a quick script to do this, it would be appreciated. Also, how do
> I do the post (is there a module I should use)?
> Thanks in advance,
> Shane
Use HTML::Form to extract the form fields.
Use LWP::UserAgent and its cohorts to do the posting.
------------------------------
Date: Sun, 21 Jan 2001 00:01:48 GMT
From: Johannes Graumann <j_graumann@hotmail.com>
Subject: matching "*"?
Message-Id: <94d8ta$bug$1@nnrp1.deja.com>
Hello,
I'm trying to match a "*" at the end of a line. Since * is a multiplier,
something like /*^/ won't work.
Please help the newbee!
Thank you, Johannes
Sent via Deja.com
http://www.deja.com/
------------------------------
Date: Sun, 21 Jan 2001 00:23:03 GMT
From: mike@stok.co.uk (Mike Stok)
Subject: Re: matching "*"?
Message-Id: <HZpa6.4311$Zc3.795632@typhoon.austin.rr.com>
In article <94d8ta$bug$1@nnrp1.deja.com>,
Johannes Graumann <j_graumann@hotmail.com> wrote:
>I'm trying to match a "*" at the end of a line. Since * is a multiplier,
>something like /*^/ won't work.
You should look at the perlre documentation for mentions of quotemeta and
to discover the correct metacharacter to use to anchor to the end of the
target.
perldoc perlre
is a place to start.
Hope this helps,
Mike
--
mike@stok.co.uk | The "`Stok' disclaimers" apply.
http://www.stok.co.uk/~mike/ |
GPG PGP Key 1024D/059913DA | Fingerprint 0570 71CD 6790 7C28 3D60
stok@colltech.com (CT - work) | 75D2 9EC4 C1C0 0599 13DA
------------------------------
Date: Sun, 21 Jan 2001 11:43:59 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: matching "*"?
Message-Id: <slrn96kc6f.bgr.mgjv@martien.heliotrope.home>
On Sun, 21 Jan 2001 00:01:48 GMT,
Johannes Graumann <j_graumann@hotmail.com> wrote:
> Hello,
>
> I'm trying to match a "*" at the end of a line. Since * is a multiplier,
> something like /*^/ won't work.
>
> Please help the newbee!
The newbie should learn to help himself by getting familiar with the
documentation.
# man perlre
[snip]
Any single character matches itself, unless it is a
metacharacter with a special meaning described here or
above. You can cause characters that normally function as
metacharacters to be interpreted literally by prefixing
them with a "\" (e.g., "\." matches a ".", not any charac
ter; "\\" matches a "\"). A series of characters matches
that series of characters in the target string, so the
pattern `blurfl' would match "blurfl" in the target
string.
[snip]
In other words: Perl comes with extensive documentation, you should
learn to use it. For most people the perldoc tool will work, until
there's something better. Start with
# perldoc perldoc
# perldoc perl
In your case you need:
/\*$/
Martien
--
Martien Verbruggen |
Interactive Media Division | Useful Statistic: 75% of the people
Commercial Dynamics Pty. Ltd. | make up 3/4 of the population.
NSW, Australia |
------------------------------
Date: Sat, 20 Jan 2001 17:20:35 -0800
From: "Godzilla!" <godzilla@stomp.stomp.tokyo>
Subject: Re: matching "*"?
Message-Id: <3A6A3963.FD295E4E@stomp.stomp.tokyo>
Johannes Graumann wrote:
> I'm trying to match a "*" at the end of a line.
> Since * is a multiplier, something like /*^/ won't work.
You will discover either method shown in my test
script below, to be quicker and more efficient.
Godzilla!
--
TEST SCRIPT:
____________
#!/usr/local/bin/perl
print "Content-type: text/plain\n\n";
# Destructive Method:
print "Destructive Chop Method:\n\n";
$line = "test line *";
# remove end of line characters if needed:
chomp ($line);
$test = chop ($line);
if ($test eq "*")
{ print " End Of Line Asterisk Found\n\n" }
else
{ print " No End Of Line Asterisk Found" }
# Non-destructive Method:
print "Non-destructive Substring Method:\n\n";
$line = "test line *";
# remove end of line characters if needed:
chomp ($line);
$test = substr ($line, -1, 1);
if ($test eq "*")
{ print " End Of Line Asterisk Found\n\n" }
else
{ print " No End Of Line Asterisk Found" }
exit;
PRINTED RESULTS:
________________
Destructive Chop Method:
End Of Line Asterisk Found
Non-destructive Substring Method:
End Of Line Asterisk Found
------------------------------
Date: Sun, 21 Jan 2001 11:32:38 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Multiprocess or multithreaded???
Message-Id: <slrn96kbh5.bgr.mgjv@martien.heliotrope.home>
On Fri, 19 Jan 2001 12:21:43 GMT,
David Sisk <davesisk@ipass.net> wrote:
> I have a batch job that will start as a serial job, then parallelize itself
> (using fork), then re-synchronize and finish as a serial job. I can do this
> one of two ways:
>
> 1) Create the part that will be parallelized as a subroutine that will only
> be run by the forked children.
> 2) Create the part that will be parallelized as a seperate Perl script,
> which will be forked, then exec'd.
>
> As best I can understand from the perlfork and perlipc docs on
> www.perldoc.com, approach 1 will (from the O/S perspective) run the forked
> children as threads in a single Perl process, while approach 2 will run the
That depends on the OS. Any OS where fork() is implemented, will run the
children as separate processes. I suspect that you read the perlfork
manual page? That only talks about the fork() emulation in Perl, which
is only used on OSes where there is no real fork(2) system call [1].
> forked/exec'd children as seperate Perl processes (again from the O/S
> perspective). [Note: I'm not using Perl threads. According to the docs,
> forking with no exec runs the children as threads, even though they appear
> as pseudo-processes to the Perl script.] I will probably have about 50-100
Again, this depends on the OS. On a POSIX compliant unix, a fork is a
real fork, and a thread is a real thread. There are OSes (noteably
Linux) where threads are implemented as heavy-weight processes, which
breaks POSIX compliance and many other things. There are OSes where
fork(2) doesn't exist (noteably MSWindows), and Perl uses threading
libraries to emulate it.
> children, and each child will be pulling data via HTTP using the LWP module,
> then parsing and storing the data using DBI. I'm developing this on NT, I
> may initially run it on NT (merely because it's convenient), but will
> probably eventually run it on Linux (because I like it better, it should be
> easier to manage, and should perform a little better.).
heh, You're mentioning the two OSes which have oddities. But then, you
are not planning on using Perl's threading (which you probably shouldn't
yet), but you are planing on using the fork() emulation on NT, and later
the real fork() on Linux, correct? So the only thing you need to be
aware of is that fork emulation isn't entirely the same as a real fork.
I'd pay attention to the perlfork manual page.. On first read I don't
see anything that could jeopardise your effort.
From what you write here, I deduce that your children, once running,
are independent of the parent (apart from their exit status), and there
will be no need for direct communication between parent and child. All
communication happens through some database (unspecified) where the
children write, and, supposedly, the parent will read, later on.
Make sure your children open the connection to the database unless both
DBI and the underlying database driver support multiple processes on one
database connection.
> Question:
> Which approach (1 or 2) is likely to work best? I'd imagine that creating
> it as multi-process (#2) will probably be more stable on both platforms,
> while creating it as multi-threaded (#1) will use less resources and
> possibly run quicker, but be less stable, on both platforms. Does anyone
> have any experience or educated opinions that would help me make this
> decision?
Your terminology seems confused. I would call 1 multi-threaded, and 2
multi-process, _if_ I had to come up with these two labels. But, on NT
both 1 and 2 will run as process threads, while on Unices, both 1 and 2
will run as separate processes. On a single OS there is no difference in
the process-thread distinction. There are however some differences that
might be of interest:
The difference between 1) and 2), as mentioned above, is marginal. you
are not planning on using IPC, apart from fork and wait, so there should
be no real difference in coding difficulty. However, there will be some
speed and resource differences which will prefer a fork without an exec
above a fork with exec.
- Most implementations of fork() will not create complete copies of the
process in memory until it is necessary. They use copy-on-write for
the memory pages, meaning that it's a lot faster than creating a new
process from scratch.
If you have a process that does 90% of its work and data manipulation
before forking, only a fraction of your process image needs to be
copied during the runtime of your child. If you exec, a new process
will need to be created, and all the memory allocated for each execed
process separately.
For Perl programs a large part of the relevant data space is perl
itself. This is almost all memory that doesn't need to be copied on a
fork.
- Most importantly, however, when you exec a new Perl process, it will
have to recompile all your code, load all the libraries, compile
those, and so on. If you do that 100 times, you are talking about a
serious number of CPU cycles used to recompile the program and the
libraries it uses, when one would have sufficed.
On NT fork() is implemented in Perl, but it uses threads. Almost the
same sort of reasoning should apply, although I am not sure how much
work the cloned interpreter needs to do. It is bound to be a lot less
than a new process though.
If you can avoid execs, do so. It is silly to rewrite existing tools so
you can encorporate them in your program. However, when designing a new
program, avoid exec. If you want to be able to use the children as
separate processes, put their code in a module, and use that module in
this script. Then write a small wrapper to use it on its own from the
command line.
But don't use exec unless you have to. It's bound to be more expensive
than fork without exec.
Martien
[1] maybe there's a flag to force the use of the fork() emulation
instead of using the system's, but I can't find it in the INSTALL
documentation.
--
Martien Verbruggen |
Interactive Media Division | Unix is user friendly. It's just
Commercial Dynamics Pty. Ltd. | selective about its friends.
NSW, Australia |
------------------------------
Date: Sun, 21 Jan 2001 01:33:49 GMT
From: "bigdawg" <ewsr1@home.com>
Subject: Newbie question - deleting directories
Message-Id: <10ra6.28041$B6.8303575@news1.rdc1.md.home.com>
Here is what I'd like to do. I am using Activestate on a Win32 system.
I'm also not clear as to which modules may be needed.
1. change to a specific directory
2. read the directory
# using readdir()
3. delete all directories older than $days_old
# using unlink()
4. write output to an existing file to track deleted directories
# using open()
------------------------------
Date: 20 Jan 2001 22:58:28 +0000
From: nobull@mail.com
Subject: Re: Newbie question
Message-Id: <u9d7dh3k6j.fsf@wcl-l.bham.ac.uk>
"bigdawg" <ewsr1@home.com> writes:
> Subject: Re: Newbie question
>90% of the time "Newbie" in subject => "person too lazy to read
manuals". Is that really the impression you want to give?
> Here is what I'd like to do. I am using Activestate on a Win32 system.
> I'm also not clear as to which modules may be needed.
>
>
> 1. change to a specific directory
> 2. read the directory
> # using readdir()
>
> 3. delete all directories older than $days_old
> # using unlink()
Like its manual entry says unlink() won't work on direcotries.
> 4. write output to an existing file to track deleted directories
> # using open()
Can't see any need for any modules there all fairly simple stuff using
just the built-in fuctions. Well you may want to use File::Find to
help with the recusive delete of a directory.
--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
------------------------------
Date: Sat, 20 Jan 2001 18:27:42 -0500
From: "Kurt Stephens" <kstep@pepsdesign.com>
Subject: Re: percentages, how?
Message-Id: <94d6ua$udp$1@slb2.atl.mindspring.net>
"snef" <snef@soneramail.nl> wrote in message
news:MPG.14d3ecb66dca7580989706@news.soneraplaza.nl...
> I've got 3 characters: a, b, c in an array (@x)
> Now I want to get one character randomly
> This is easy. Something like $a[rand 3].
>
> but now i want to add some winning percentages. The change to get b must
> be 80%.
> How can I do this?
For a quick & dirty solution, Godzilla!'s reply certainly does the trick. A
slower but more general solution would be to create a probability map for
the elements and then apply some sort of quanitization to the output of
rand().
[begin code]
use strict;
use warnings;
# Start with an array of values and their associated
# (percent) probabilities.
my @probmap = (
['a' => 10],
['b' => 80],
['c' => 3],
['d' => 7],
);
# As in intermediate step we generate a set of high/low
# quanitization points to each array element.
my $limit = 0;
foreach my $item (@probmap) {
$item->[2] = $limit; # low value
$item->[3] = $limit += $item->[1]/100; # high value
}
# getitem() generates a random number and returns the
# corresponding value.
sub getitem {
my $n = rand;
foreach my $item (@probmap) {
return $item->[0]
if $n >= $item->[2] && $n < $item->[3];
}
}
# Finally a test....
my %test;
my $samples = 10000;
$test{getitem()}++ for (1..$samples);
printf("$_ => %.4f\n", $test{$_}/$samples) foreach sort keys %test;
[end code]
Of course, you could also apply some mathematical function to the output of
rand() to alter the distribution.
# Assume 0 <= f(x) < 1 for all x: 0 <= x < 1
my @items = qw(a b c);
$value = $items[f(rand) * @items];
HTH,
Kurt Stephens
------------------------------
Date: 21 Jan 2001 00:12:24 GMT
From: abigail@foad.org (Abigail)
Subject: Re: percentages, how?
Message-Id: <slrn96kab8.hms.abigail@tsathoggua.rlyeh.net>
snef (snef@soneramail.nl) wrote on MMDCXCIX September MCMXCIII in
<URL:news:MPG.14d3ecb66dca7580989706@news.soneraplaza.nl>:
$$ Hi,
$$
$$ I've got a problem.
$$
$$ imagine:
$$
$$ I've got 3 characters: a, b, c in an array (@x)
$$ Now I want to get one character randomly
$$ This is easy. Something like $a[rand 3].
$$
$$ but now i want to add some winning percentages. The change to get b must
$$ be 80%.
$$ How can I do this?
There are various ways. A simple one is:
my @tmp = (('a') x 10, ('b') x 80, ('c') x 10);
my $rand_char = $tmp [rand @tmp];
But this can use quite a lot of memory depending on the relative
frequencies. It also requires them to have an integer common multiply.
(it won't work if the ratio a:b == 1:sqrt(2))
Another is:
my @tmp = ([a => 1], [b => 8], [c => 1]);
my $c = 0;
my $rand_char;
foreach my $element (@tmp) {
$c += $element -> [1];
$rand_char = $element -> [0] if rand $c < $element -> [1];
}
Proof that the latter algorithm is unbiased:
Let the S = (s .. s ) be the set to be sampled from. Let f be
1 n i
the relative frequency of s (1 <= i <= n).
i
n
---
Let F == \ f (the sum of all frequencies)
/ i
---
i=1
Then the probability that element s is the final selected element is:
k
n j-1
--------- ---
f | | \ f
k | | / i
| | ---
| | i=1
------- * | | -------
k | | j
--- | | ---
\ f | | \ f
/ i | | / i
--- | | ---
i=1 j=k+1 i=1
(s selected) (s not selected, k < j <= n)
k j
This reduces to:
k
---
f \ f f
k / i k
--- f
i=1 k
------- * ------- == ------- == --
k n n F
--- --- ---
\ f \ f \ f
/ i / i / j qed
--- --- ---
i=1 i=1 i=1
Abigail
--
perl -wle 'eval {die [[qq [Just another Perl Hacker]]]};; print
${${${@}}[$#{@{${@}}}]}[$#{${@{${@}}}[$#{@{${@}}}]}]'
------------------------------
Date: Sat, 20 Jan 2001 16:47:27 -0800
From: "Godzilla!" <godzilla@stomp.stomp.tokyo>
Subject: Re: percentages, how?
Message-Id: <3A6A319F.729FEB07@stomp.stomp.tokyo>
Kurt Stephens wrote:
> "snef" wrote:
> > I've got 3 characters: a, b, c in an array (@x)
> > Now I want to get one character randomly
> > This is easy. Something like $a[rand 3].
> > but now i want to add some winning percentages.
> > The change to get b must be 80%.
> > How can I do this?
> For a quick & dirty solution, Godzilla!'s reply certainly
> does the trick. A slower but more general solution would
> be to create a probability map for the elements and then
> apply some sort of quanitization to the output of rand().
> [begin code]
(snipped interesting code)
Even quicker and certainly more dirty than setting
percentage odds manually via a populated array, would
be to work with pure numbers.
$random = int(rand(10));
# backup for older Perl versions:
if (!($random))
{ srand; $random = int(rand(10)); }
# 80% selection of b:
if ($random == 0)
{ $answer = "a"; }
elsif ($random == 1)
{ $answer = "c"; }
else
{ $answer = "b"; }
I am curious, but not curious enough to test, what
effect a lack of true randomness of rand would have
on large scale usage of percentage based programs.
It could be surmised instead of rounding off rand
to whole numbers and rather dealing with decimal
based numbers would lend to better randomness for
a higher quality percentage program.
However, rounding off rand to whole integers, in
itself, would include inherent randomness. It could
be argued, rounding off or using decimal numbers,
either would not display significant differences.
Godzilla!
------------------------------
Date: Sat, 20 Jan 2001 19:40:36 -0500
From: "Hogan" <hogan@go away.com>
Subject: Perl Crashes on my Win2k Box
Message-Id: <t6kc1unp5jhea2@corp.supernews.com>
I am attempting to run a script and I get an error that says Perl has
generated an error and must be shut down. Anybody have any idea why this is?
Any help would be appreciated.
Thanks.
------------------------------
Date: Sat, 20 Jan 2001 20:39:28 -0500
From: Emrah Diril <ediril@ece.wpi.edu>
Subject: Perl in C
Message-Id: <Pine.OSF.4.21.0101202039180.27544-100000@ece.wpi.edu>
Hi All,
I want to use some Perl functions that I wrote in C. I looked at the
documentation at perl.com (How to embed perl in your C program), but
it is not helpful to me because I am trying to use Borland Turbo C to
compile my programs.
Does anyone know how to embed Perl functions into C using Borland Turbo C
or Microsoft C?
Please reply via e-mail.
Thanks.
Emrah
------------------------------
Date: Sat, 20 Jan 2001 20:38:59 -0500
From: Emrah Diril <ediril@ece.wpi.edu>
Subject: Perl in C
Message-Id: <Pine.OSF.4.21.0101202036430.27544-100000@ece.wpi.edu>
Hi All,
I want to use some Perl functions that I wrote in C. I looked at the
documentation at perl.com (How to embed perl in your C program), but
it is not helpful to me because I am trying to use Borland Turbo C to
compile my programs.
Does anyone know how to embed Perl functions into C using Borland Turbo C
or Microsoft C?
Please reply via e-mail.
Thanks.
Emrah
------------------------------
Date: 20 Jan 2001 23:27:19 GMT
From: abigail@foad.org (Abigail)
Subject: Re: Powerful Technique 3606
Message-Id: <slrn96k7mn.hms.abigail@tsathoggua.rlyeh.net>
Bart Lateur (bart.lateur@skynet.be) wrote on MMDCXCIX September MCMXCIII
in <URL:news:qhmj6t48suqg5alkh9dealk4r43effahl9@4ax.com>:
() zoycit@email.com wrote:
()
() >pmpmofcqxzgkvsvpobtjfurjdfxnjqmo
()
() This was the most sensible sentence in the whole post. ;-)
()
() Does anybody know how to write a regex that matches this kind of
() neonsense? You can easily recognize it by eye, but... is there really a
() pattern? At least 4 consonants in a row?
Yeah, just don't post a Perl program that uses 'dbmclose', 'endgrent',
'endprotoent', 'endpwent', 'fcntl', 'getgrgid', 'getgrnam', 'getpgrp',
'getpwnam', 'length', 'msgctl', 'msgget', 'msgrcv', 'msgsnd', 'shmctl',
'shmget', 'shmread', 'shmwrite', 'sqrt', or 'substr'.
Don't post in Dutch either.
() I thought of applying a filter that works on subject lines ending with a
() number. The only problem is that it would also kill legitimite (=
() non-spam) posts with titles like "problem on Windows 2000".
Added benefit, I'd say. ;-)
Abigail, who already kills posts with Windows 2000 in the subject.
--
perl -we 'print split /(?=(.*))/s => "Just another Perl Hacker\n";'
------------------------------
Date: Sun, 21 Jan 2001 10:56:14 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Powerful Technique 3606
Message-Id: <slrn96k9cu.bgr.mgjv@martien.heliotrope.home>
[I never saw the original message. One of the upstream news servers has
cancelled it for being spam. Complain to your news admin if you can
still find it. It should have been cancelled]
On Sat, 20 Jan 2001 18:37:04 GMT,
Bart Lateur <bart.lateur@skynet.be> wrote:
> zoycit@email.com wrote:
>
>>pmpmofcqxzgkvsvpobtjfurjdfxnjqmo
>
> This was the most sensible sentence in the whole post. ;-)
>
> Does anybody know how to write a regex that matches this kind of
> neonsense? You can easily recognize it by eye, but... is there really a
> pattern? At least 4 consonants in a row?
\begin{offtopic}
Some words that you might encounter in messages that have more than 4
consonants in a row are dumbstruck, catchphrase or weltschmerz (there
are others, more obscure), and of course the Dutch angstschreeuw and the
German Angstschrei would make it harder even. Other languages have
longer sequences. Oh, and zachtstschreiende makes it slightly longer
again, but I doubt you'd find that word in any natural text.
\end{offtopic}
If you need a pattern, it would probably not be a simple regex. A
minimum wordlength, combined with sequences of consoants. But the
giveaway probably would be that there are going to be sequences of
consonants that don't appear in any language (that I'd be interested
in). Figuring out those sequences could be done with a grep on
/usr/dict/words for each appropriate language.
> I thought of applying a filter that works on subject lines ending with a
> number. The only problem is that it would also kill legitimite (=
> non-spam) posts with titles like "problem on Windows 2000".
I already kill those, because I am normally not interested in windows
specific problems :)
Has there been a flood of these lately or so? If so, complain to your
news admin. None of them arrived here.
Martien
--
Martien Verbruggen |
Interactive Media Division | That's not a lie, it's a
Commercial Dynamics Pty. Ltd. | terminological inexactitude.
NSW, Australia |
------------------------------
Date: 20 Jan 2001 17:10:23 -0600
From: ranyartolias@hotmail.com (Ranyart Olias)
Subject: Question re: Mail::Internet
Message-Id: <3a6a1a6e.61698470@news-west.newscene.com>
I am trying to stuff the value of a message body into an array.
Mail::Internet allows me to write to a file handle:
use Mail::Internet;
open SPAM, "/home/user/message.txt";
$spam = Mail::Internet->new( *SPAM );
close SPAM;
open BODY, ">/home/tag-net/body.txt";
$spam->print_body(\*BODY);
What I would like to do, however, is just
stuff contents of the message body into an
array, without opening any files.
This may be a stupid question, but, how
do I do this? Any comments or flames which
might profide a clue apprectiated.
------------------------------
Date: 20 Jan 2001 23:11:27 +0000
From: nobull@mail.com
Subject: Re: redirect and cookie (+domain) does not work!
Message-Id: <u94ryt3jkw.fsf@wcl-l.bham.ac.uk>
Jeffery Cann <jccann@catholic.org> writes:
> I am trying to set a cookie for the server where the user is to be
> redirected.
Give up. You can't. This has nothing whatever to do with Perl. You
might just as well say you are trying to write a cheque on your cheque
book that will be drawn on someone else's bank account.
--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
------------------------------
Date: Sun, 21 Jan 2001 11:38:10 +1100
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Spawning Parallel Processes
Message-Id: <slrn96kbri.bgr.mgjv@martien.heliotrope.home>
{please, in the future, put your reply _after_ the suitably trimmed
text you reply to. It makes your post easier to read, the thread easier
to follow, and is in accordance with the guidelines on this group, and
Usenet in general}
On Sat, 20 Jan 2001 17:27:05 GMT,
David Sisk <davesisk@ipass.net> wrote:
><arkconfused@hotmail.com> wrote in message
> news:94au46$lrp$1@nnrp1.deja.com...
>> I have been trying to look at away to have a perl script spawn off 7
>> processes and to have them run at the same time. Each process telnets
>> into a different server. Any ideas?
You are posting from deja. Did you know they have an archive of posts to
this group, as well as many others? Did you bother to search it?
> I know your pain. I couldn't find a good example of this anywhere (or at
> least not one I understood) Search this newsgroup for a posting called
> "fork lots of children". A fellow posted an example a couple of days ago
> that shows exactly how to do what you want. It doesn't use signals, which
> (to my understanding) is a good thing.
It is a reasonably frequently asked question. I suspect you are
referring to Randal Schwartz with the 'A fellow' bit?
http://www.stonehenge.com/merlyn/LinuxMag/
look at columns 15 and 16.
Martien
--
Martien Verbruggen |
Interactive Media Division | Never hire a poor lawyer. Never buy
Commercial Dynamics Pty. Ltd. | from a rich salesperson.
NSW, Australia |
------------------------------
Date: 16 Sep 99 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Digest Administrivia (Last modified: 16 Sep 99)
Message-Id: <null>
Administrivia:
The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc. For subscription or unsubscription requests, send
the single line:
subscribe perl-users
or:
unsubscribe perl-users
to almanac@ruby.oce.orst.edu.
| NOTE: The mail to news gateway, and thus the ability to submit articles
| through this service to the newsgroup, has been removed. I do not have
| time to individually vet each article to make sure that someone isn't
| abusing the service, and I no longer have any desire to waste my time
| dealing with the campus admins when some fool complains to them about an
| article that has come through the gateway instead of complaining
| to the source.
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 108
**************************************