[29182] in Perl-Users-Digest
Perl-Users Digest, Issue: 426 Volume: 11
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri May 11 11:10:02 2007
Date: Fri, 11 May 2007 08:09:08 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Fri, 11 May 2007 Volume: 11 Number: 426
Today's topics:
Re: How to concatenate cookies <paduille.4061.mumia.w+nospam@earthlink.net>
Re: how to join array into array <bik.mido@tiscalinet.it>
Re: Identify if a scalar is int, double or text <sisyphus1@nomail.afraid.org>
Re: Identify if a scalar is int, double or text anno4000@radom.zrz.tu-berlin.de
Re: Identify if a scalar is int, double or text <wahab-mail@gmx.de>
Re: Identify if a scalar is int, double or text <thepoet_nospam@arcor.de>
Re: need a quick script <bik.mido@tiscalinet.it>
Re: need a quick script <bik.mido@tiscalinet.it>
Re: need a quick script <bik.mido@tiscalinet.it>
Re: need a quick script <bik.mido@tiscalinet.it>
Net::FTP and firewalls (was:Forcing CPAN to ncftp??) <drawson1.take.this.out@earthlink.dot.net>
Re: Net::FTP and firewalls <spamtrap@dot-app.org>
Perl regularexpression problem with the Input file <betterdie@gmail.com>
Re: Perl regularexpression problem with the Input file <mritty@gmail.com>
Process supervision and exception titetluc@gmail.com
Re: Process supervision and exception xhoster@gmail.com
Solve a statistics problem <brundlefly76@hotmail.com>
Re: Solve a statistics problem <mritty@gmail.com>
Re: Solve a statistics problem <ignoramus6365@NOSPAM.6365.invalid>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Fri, 11 May 2007 11:35:14 GMT
From: "Mumia W." <paduille.4061.mumia.w+nospam@earthlink.net>
Subject: Re: How to concatenate cookies
Message-Id: <SxY0i.9936$j63.2717@newsread2.news.pas.earthlink.net>
On 05/11/2007 12:09 AM, dr_phill123@yahoo.com wrote:
> On May 10, 11:35 pm, "Mumia W." <paduille.4061.mumia.w
> +nos...@earthlink.net> wrote:
>> You can put several values into a single cookie like so:
>>
>> my $cookie = $query->cookie(
>> -domain => $domainname,
>> -name => 'customfields',
>> -value => \@custom_fields
>> );
>> print $query->header(-cookie => $cookie);
>>
>> Read the CGI docs again: perldoc CGI
>
> Thanks, but I am actually looking for each cookie to be seperate, so
> have multiple cookies in one variable $cookie. The docs says:
>
> you may concatenate the cookies together with ``; ''
>
> I am not sure what those characters mean ``; " ?
>
What docs are you talking about? I can't find that exact language in
either CGI.pm's POD, or in RFC2109. In RFC2109, something close to the
syntax you talk about is described, but I can't find anything that
suggests that CGI.pm supports that.
The description of raw_cookie() is a little confusing. While you can get
cookies which have been concatenated with "; " (semicolon and space)
from CGI::raw_cookie(), there does not seem to be a way to create such
cookies.
Anyway, RFC2109 says that cookies are separated by commas:
> Informally, the Set-Cookie response header comprises the token Set-
> Cookie:, followed by a comma-separated list of one or more cookies.
------------------------------
Date: Fri, 11 May 2007 16:02:39 +0200
From: Michele Dondi <bik.mido@tiscalinet.it>
Subject: Re: how to join array into array
Message-Id: <llt843dkvrg513bm9o3g9k8ie7ckj3tgis@4ax.com>
On 6 May 2007 10:41:55 -0700, Tradeorganizer
<tradeorganizer@gmail.com> wrote:
>$VAR1 = [
> [
> 1,
> 2,
> 3,
> 4,
> 2,
> 2,
> 3,
> 4
> ],
<snip>
>where as i need like
>$VAR1 = [ [ 1, 2, 3, 4, 2, 2, 3, 4 ],
AFAICS it's the same. But for visualization. Try ->Indent(0).
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
.'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
------------------------------
Date: Fri, 11 May 2007 22:23:42 +1000
From: "Sisyphus" <sisyphus1@nomail.afraid.org>
Subject: Re: Identify if a scalar is int, double or text
Message-Id: <46446045$0$27107$afc38c87@news.optusnet.com.au>
"Klaus" <klaus03@gmail.com> wrote in message
news:1178874197.967635.164880@n59g2000hsh.googlegroups.com...
> Hello,
>
> I have a list of 4 scalars
> my @L = (3, '3', 3.0, '3.0');
>
> The first is obviously an int, the second is text, the third a double
> and the last is text again.
>
> I want to write a subroutine type_id which returns either 'int',
> 'double', 'text' (or '?') for each of the scalars, so that
>
> print type_id($_), ' ' for (@L); print "\n";
>
> results in the following output:
>
> int text double text
>
> I have found a solution where I use Devel::Peek, call Dump(), redirect
> STDERR into an "in-memory" file ( \$data ) and analyse the "in-memory"
> content:
>
> $data =~ /^SV = IV(0x/ # for ints
> $data =~ /^SV = NV(0x/ # for doubles
> $data =~ /^SV = PV(0x/ # for text
>
> but I wanted to know whether there is a better way.
There's probably already a module that does this. (Scalar-Util-Numeric might
be one such module.)
It's fairly straightforward with XS or Inline::C. Be aware that a variable
can change from one type to another in rather sneaky ways - as the following
demonstrates:
use warnings;
use Inline C => Config =>
BUILD_NOISY => 1;
use Inline C => <<'END_OF_C_CODE';
int _itsa (SV * x) {
if(SvIOK(x)) return 1;
if(SvNOK(x)) return 2;
if(SvPOK(x)) return 3;
}
END_OF_C_CODE
my @L = (3, '3', 3.0, '3.0');
print type_id($_), ' ' for (@L); print "\n";
# int text double text
my $string = '7';
print type_id($string), "\n"; # text
$string *= 1;
print type_id($string), "\n"; # int
my $var = ~0;
print type_id($var), "\n"; # int
$var *= -1;
print type_id($var), "\n"; # double (though that might
# differ on 64-bit perls)
sub type_id {
return "int" if (_itsa($_[0]) == 1);
return "double" if(_itsa($_[0]) == 2);
return "text" if(_itsa($_[0]) == 3);
return "unknown";
}
------------------------------
Date: 11 May 2007 12:49:28 GMT
From: anno4000@radom.zrz.tu-berlin.de
Subject: Re: Identify if a scalar is int, double or text
Message-Id: <5aj72oF2pqe7fU1@mid.dfncis.de>
Klaus <klaus03@gmail.com> wrote in comp.lang.perl.misc:
> Hello,
>
> I have a list of 4 scalars
> my @L = (3, '3', 3.0, '3.0');
>
> The first is obviously an int, the second is text, the third a double
> and the last is text again.
>
> I want to write a subroutine type_id which returns either 'int',
> 'double', 'text' (or '?') for each of the scalars, so that
>
> print type_id($_), ' ' for (@L); print "\n";
>
> results in the following output:
>
> int text double text
It is very rare in Perl that you need to know these differences.
> I have found a solution where I use Devel::Peek, call Dump(), redirect
> STDERR into an "in-memory" file ( \$data ) and analyse the "in-memory"
> content:
[snip]
You can tell the difference between a number or a string from
the behavior of bitwise boolean operations:
print $_ & ~$_ ? 'str ' :'num ' for (3, '3', 3.0, '3.0');
print "\n";
There is no similar way to tell the difference between an integer
and a float that happens to have an integer value.
The B::* set of modules should have the means to get the info
without catching printed output.
Anno
------------------------------
Date: Fri, 11 May 2007 15:32:02 +0200
From: Mirco Wahab <wahab-mail@gmx.de>
Subject: Re: Identify if a scalar is int, double or text
Message-Id: <f21rj2$jgl$1@mlucom4.urz.uni-halle.de>
Klaus wrote:
> Hello,
>
> I have a list of 4 scalars
> my @L = (3, '3', 3.0, '3.0');
>
> The first is obviously an int, the second is text, the third a double
> and the last is text again.
>
> I want to write a subroutine type_id which returns either 'int',
> 'double', 'text' (or '?') for each of the scalars, so that
>
> print type_id($_), ' ' for (@L); print "\n";
>
> results in the following output:
>
> int text double text
As Sisyphus mentioned, that might be tricky and
not very reliable, because Perl 'DWYM'-ifies
it's scalars every time depending on the context.
The situations where you would really need this
detailed information would also (imho) justify
looking deep into the perl (as Sisyphus did with
XS code or with the B modules).
After reading Anno's idea (bitwise complement), I
tried to combine this with Scalar::Util::Numeric
by a quick hack:
...
use Scalar::Util::Numeric qw(isnum isint isfloat);
no strict 'refs';
for my $l (3, '3', 3.0, '3.0', 'abc') {
print "[ $l ]\tlooks like ", $l & ~$l ? 'string' :'number', ' | ';
print map "$_, ", grep $_->($l), qw' isint isfloat ' ;
print "\n"
}
...
which prints:
[ 3 ] looks like number | isint,
[ 3 ] looks like string | isint,
[ 3 ] looks like number | isint,
[ 3.0 ] looks like string | isfloat,
[ abc ] looks like string |
Just an idea ...
Regards
M.
------------------------------
Date: Fri, 11 May 2007 16:28:04 +0200
From: Christian Winter <thepoet_nospam@arcor.de>
Subject: Re: Identify if a scalar is int, double or text
Message-Id: <46447d75$0$10188$9b4e6d93@newsspool4.arcor-online.net>
Klaus wrote:
> I have a list of 4 scalars
> my @L = (3, '3', 3.0, '3.0');
>
> The first is obviously an int, the second is text, the third a double
> and the last is text again.
>
> I want to write a subroutine type_id which returns either 'int',
> 'double', 'text' (or '?') for each of the scalars, so that
>
> print type_id($_), ' ' for (@L); print "\n";
>
> results in the following output:
>
> int text double text
>
> I have found a solution where I use Devel::Peek, call Dump(), redirect
> STDERR into an "in-memory" file ( \$data ) and analyse the "in-memory"
> content:
>
> $data =~ /^SV = IV(0x/ # for ints
> $data =~ /^SV = NV(0x/ # for doubles
> $data =~ /^SV = PV(0x/ # for text
>
> but I wanted to know whether there is a better way.
The best answer to your question is still to be found in
perldoc -q scalar.is.a.number
As Mirco already wrote, variables in Perl DWIM, but don't neccessarily
hold the data like it was assigned to them. To make things complicated
Perl knows dualvars, meaning variables that hold values of different
types at once (a good example is the magic $! variable).
In such a case determining what "type" the value is of depends solely
on the context it is used in. Consider this example:
------------------------------------------------
#/usr/bin/perl
use Scalar::Util qw(dualvar);
Devel::Peek;
my $x = dualvar 13, "14.5";
Dump( $x );
print "$x = ", 0 + $x, $/;
__END__
SV = PVNV(0x2ba2c) at 0x3253454
REFCNT = 1
FLAGS = (PADBUSY,PADMY,IOK,POK,pIOK,pPOK)
IV = 13
NV = 0
PV = 0x32525ac "14.5"\0
CUR = 4
LEN = 8
14.5 = 13
------------------------------------------------
The scalar above holds an integer value as well as a string
(that happens to look quite 'floaty') and has IOK as well as POK
set.
-Chris
------------------------------
Date: Fri, 11 May 2007 15:47:36 +0200
From: Michele Dondi <bik.mido@tiscalinet.it>
Subject: Re: need a quick script
Message-Id: <cts843pv4377amfpoomotm9vg9gn79o0h5@4ax.com>
On Sun, 6 May 2007 19:51:50 +0200, "Lambik" <lambik@kieffer.nl> wrote:
>Such a hopeless question and i still learned something. I would have done:
>
>return substr($first, 0, 1) . $last
>
>Didn't know the return was optional
It's not optional, it's implicit. I like to rely on this. Somebody
else prefer to be explicit. Some like to be explicit *if* there are
explicity early return()s anyway. That sounds sensible, indeed.
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
.'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
------------------------------
Date: Fri, 11 May 2007 15:50:37 +0200
From: Michele Dondi <bik.mido@tiscalinet.it>
Subject: Re: need a quick script
Message-Id: <i1t843dfc39do8klp3ei9nr8tkqein45gt@4ax.com>
On Sun, 6 May 2007 19:01:12 -0500, Tad McClellan
<tadmc@augustmail.com> wrote:
>> After all, this is Perl, not PHP...
>
>
>You should program with the maintenance programmer in mind no
>matter what programming language you are using.
But the maintenance programmer I have in mind knows Perl enough well
maybe not to the point of being a guru, but to at least know about
implicit return. Anyway I only write lvalue subs nowadays which break
with explicit return, so I'm forced to do it that way. Didn't I tell
you? ;-)
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
.'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
------------------------------
Date: Fri, 11 May 2007 15:54:46 +0200
From: Michele Dondi <bik.mido@tiscalinet.it>
Subject: Re: need a quick script
Message-Id: <jct8431lhs9oqpkm1e97vvu5538p191a32@4ax.com>
On Tue, 8 May 2007 02:43:13 +0200, "Petr Vileta"
<stoupa@practisoft.cz> wrote:
>> This alphabet has single 'C' and 'H' as individual characters, too. How do
>> you -as a human(!)- know, if the first is supposed to be 'C' or 'Ch'?
>>
>In the Czech language it is very simple. If I found 'C' followed by 'H' or
>'h' then this MUST be 'CH' (or 'Ch'). In other language I don't know.
But isn't it represented with a single gliph, then?
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
.'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
------------------------------
Date: Fri, 11 May 2007 15:56:47 +0200
From: Michele Dondi <bik.mido@tiscalinet.it>
Subject: Re: need a quick script
Message-Id: <9ft843psikh6u4o6h1sb25onjqojkkjee8@4ax.com>
On Sun, 06 May 2007 17:39:31 -0400, Sherm Pendley
<spamtrap@dot-app.org> wrote:
>> Does anyone have a script lying around that will take firstname
>> lastname and create first initial lastname: Bob Schmo --> BSchmo
>
>Careful with that! I worked in an office where we generated logins using
>the same scheme. That changed when Sue Hitts needed a login. :-) (First
>name changed to protect the innocent.)
Has anybody seen Mark Hunt? (Op. Cit.)
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
.'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
------------------------------
Date: Fri, 11 May 2007 07:18:45 -0400
From: Dan Rawson <drawson1.take.this.out@earthlink.dot.net>
Subject: Net::FTP and firewalls (was:Forcing CPAN to ncftp??)
Message-Id: <46444e3a$0$9291$88260bb3@news.teranews.com>
Sherm Pendley wrote:
> Dan Rawson <drawson1.take.this.out@earthlink.dot.net> writes:
>
>> Is there a way to prevent CPAN from using any method except ncftp??
>
> None that I know of.
>
>> I've got ncftp working through our firewall, but have consistent
>> troubles with Net::FTP and LWP.
>
> Why not fix the troubles with Net::FTP? If your firewall requires passive
> transfers, try setting the FTP_PASSIVE environment variable to non-zero.
>
> sherm--
>
:-)) That would be my first choice . . . . it's an authentication problem of
some type.
ncftp is set to use what they call a "type 7" firewall, which looks like
this in the ncftp config file:
# type 7: Connect to firewall host, but send
# "USER user@real.host.name fwuser" and
# "PASS pass" followed by
# "ACCT fwpass" to complete the login.
ftp_passive is on in the ncftp config file. However, setting FTP_PASSIVE in
the environment doesn't change the behavior.
I can set the proxy host and port, but I can't figure any way (from the
Net::FTP documentation) to set the required user name and password for the
firewall.
Dan
------------------------------
Date: Fri, 11 May 2007 08:00:28 -0400
From: Sherm Pendley <spamtrap@dot-app.org>
Subject: Re: Net::FTP and firewalls
Message-Id: <m2lkfvmuxv.fsf@local.wv-www.com>
Dan Rawson <drawson1.take.this.out@earthlink.dot.net> writes:
> :-)) That would be my first choice . . . . it's an authentication problem of
> some type.
>
> ncftp is set to use what they call a "type 7" firewall, which looks like
> this in the ncftp config file:
>
> # type 7: Connect to firewall host, but send
> # "USER user@real.host.name fwuser" and
> # "PASS pass" followed by
> # "ACCT fwpass" to complete the login.
>
> ftp_passive is on in the ncftp config file. However, setting FTP_PASSIVE in
> the environment doesn't change the behavior.
>
> I can set the proxy host and port, but I can't figure any way (from
> the Net::FTP documentation) to set the required user name and password
> for the firewall.
Does this recipe work for you?
<http://perldoc.perl.org/Net/libnetFAQ.html#I-am-behind-an-FTP-proxy-firewall%2c-but-cannot-access-machines-outside-%3f>
If it does, then I'd imagine that CPAN.pm could be patched to use it.
sherm--
--
Web Hosting by West Virginians, for West Virginians: http://wv-www.net
Cocoa programming in Perl: http://camelbones.sourceforge.net
------------------------------
Date: 11 May 2007 07:19:40 -0700
From: paul <betterdie@gmail.com>
Subject: Perl regularexpression problem with the Input file
Message-Id: <1178893180.506367.66730@e65g2000hsc.googlegroups.com>
Hello,
The following code is to read data from the file and store it into the
hash-arrayreference, it seems to work for the data in the code but not
for the file.
===== the file that the program reading is
1- what is psychologist?
a- study of mental processing
b- study about human intelligent
c- study both human and animal
d- study biolpsychology
2- what is neuron?
a- a connection between cell body
b- a electro chemical
c- chimal reaction between oxygen and water
d- part of soma
===============
#!/usr/bin/perl
use strict;
use warnings;
my $file_name = shift;
my %question_answer_haf;
open(OFILE, "$file_name") || die("Can't open the file: $!");
while(<OFILE>){
my $question;
my @answers;
#print "$2\n" if(/(\d)+\s*-\s*(.*)/) ;
#print "$2\n" if(/(?i)(\w)+\s*-\s*(.*)/);
if(/\d+\s*-\s*(.*)/) {
$question = ${1};
}
if(/(?i)(\w)+\s*-\s*(.*)/) {
push @{$question_answer_haf{$question}}, $2;
}
}
close(OFILE);
==========================
the work version,
my %hashQuestion= (
"1 - What is Psychology? "=>[ "A- study about mind and mental
concept*",
"B- is part of a seudopsychology",
"C- about all the life and ",
"d- none of the above"],
"2- what is neuron? "=>[ "a- is an electro in the body* ",
"b- a fuid in the boyd"]
);
my %hash2 ;
foreach my $question1 (keys %hashQuestion) {
print "$question1 \n";
foreach my $i (0..$#{$hashQuestion{$question1}}) {
print $hashQuestion{$question1}[$i] . "\n";
push @{$hash2{$question1}}, $hashQuestion{$question1}
[$i];
}
}
thank
------------------------------
Date: 11 May 2007 07:57:04 -0700
From: Paul Lalli <mritty@gmail.com>
Subject: Re: Perl regularexpression problem with the Input file
Message-Id: <1178895423.940084.242760@p77g2000hsh.googlegroups.com>
On May 11, 10:19 am, paul <better...@gmail.com> wrote:
> Hello,
>
> The following code is to read data from the file and store it into the
> hash-arrayreference, it seems to work for the data in the code but not
> for the file.
> ===== the file that the program reading is
> 1- what is psychologist?
> a- study of mental processing
> b- study about human intelligent
> c- study both human and animal
> d- study biolpsychology
> 2- what is neuron?
> a- a connection between cell body
> b- a electro chemical
> c- chimal reaction between oxygen and water
> d- part of soma
> ===============
> #!/usr/bin/perl
>
> use strict;
> use warnings;
>
> my $file_name = shift;
> my %question_answer_haf;
>
> open(OFILE, "$file_name") || die("Can't open the file: $!");
>
> while(<OFILE>){
> my $question;
You're defining $question within the scope of a single iteration of
the while loop. That means as soon as this iteration is done, this
$question goes out of scope. On the next iteration, a brand new
$question - still undefined - is created.
> my @answers;
> #print "$2\n" if(/(\d)+\s*-\s*(.*)/) ;
> #print "$2\n" if(/(?i)(\w)+\s*-\s*(.*)/);
>
> if(/\d+\s*-\s*(.*)/) {
> $question = ${1};
$question is set in this iteration of the loop
> }
> if(/(?i)(\w)+\s*-\s*(.*)/) {
> push @{$question_answer_haf{$question}}, $2;
But this $question is a completely separate instance, and has nothing
to do with the $question that was set above.
> }
>
> }
Move $question's definition to above the while loop.
Also, change your second if() to an elsif, as \w matches digits as
well, so you're going to be including the question as one of its own
possible answers.
Paul Lalli
------------------------------
Date: 11 May 2007 04:39:01 -0700
From: titetluc@gmail.com
Subject: Process supervision and exception
Message-Id: <1178883541.151710.324830@q75g2000hsh.googlegroups.com>
Hi all
My problem: I have a library managing Perl objects
An object may be composed of several processes
Here is an example of my library (be careful: the sleep call are used
only for debug purpose !!)
#!/usr/bin/perl -w
use strict;
package obj;
sub new
{
my $class = shift;
my %param = @_;
my %obj;
$obj{name} = $param{name};
my @pid;
$pid[0] = fork();
if (!$pid[0]){
sleep(5);
# the treatment to be declared here
exit(1);
}
print "PID: $pid[0]";
$pid[1] = fork();
if (!$pid[1]){
sleep(10000);
# the treatment to be declared here
}
print "PID: $pid[1]";
bless \%obj, $class;
}
sub action
{
my $obj = shift;
sleep(10000);
}
__END__
I would like my library to raise an exception when one of the process
dies for any reasons.
A code, implementing the process death detection and the exception
raise, could be:
sub watch
{
my @pid = @_;
my $p = waitpid(-1,0);
my $to_kill = $pid[0];
if ($p == $to_kill){
$to_kill = $pid[1];
}
kill 15, $to_kill;
die "goodbye cruel world\n";
}
I could then use the library as follows:
package main;
sub main
{
my $o1 = obj->new(name=> 'o1');
my $o2 = obj->new(name=> 'o2');
eval {$o1->action();};
if ($@){
print "o1 killed\n";
}
eval {$o2->action();};
if ($@){
print "o2 killed\n";
}
}
main();
1;
My problem is that I don't know how to call the 'watch' function
. I could call it in a CHLD sig handler, but in this case I do not
know which object "generates" the CHLD signal. In addtion, the method
is very intrusive because it requires the signal handler declaration
in the main module.
. I could declare a thread supervision per object (adding the line
threads->new(\&watch, @pid)->detach(); in the obj::new constructor)
but this does not run (message 'thread failed to start: goodbye cruel
world')
I didn't find any information in this group nor in perldoc
Any idea ?
Thanks
Gaetan
------------------------------
Date: 11 May 2007 14:07:01 GMT
From: xhoster@gmail.com
Subject: Re: Process supervision and exception
Message-Id: <20070511100704.311$wE@newsreader.com>
titetluc@gmail.com wrote:
> Hi all
>
> My problem: I have a library managing Perl objects
> An object may be composed of several processes
>
> Here is an example of my library (be careful: the sleep call are used
> only for debug purpose !!)
The above doesn't really describe what it is you want to do. And your code
also doesn't do what you want it to do. Between the two of those, I'm left
wondering just what it is you want to do.
> #!/usr/bin/perl -w
> use strict;
>
> package obj;
>
> sub new
> {
> my $class = shift;
> my %param = @_;
> my %obj;
> $obj{name} = $param{name};
>
> my @pid;
> $pid[0] = fork();
> if (!$pid[0]){
> sleep(5);
> # the treatment to be declared here
> exit(1);
> }
> print "PID: $pid[0]";
> $pid[1] = fork();
> if (!$pid[1]){
> sleep(10000);
> # the treatment to be declared here
> }
> print "PID: $pid[1]";
>
> bless \%obj, $class;
> }
@pid is lexical to the sub new, and isn't saved anywhere, so once new
finishes, @pid is lost.
>
> sub action
> {
> my $obj = shift;
> sleep(10000);
> }
>
> __END__
>
> I would like my library to raise an exception when one of the process
> dies for any reasons.
>
> A code, implementing the process death detection and the exception
> raise, could be:
>
> sub watch
> {
> my @pid = @_;
> my $p = waitpid(-1,0);
> my $to_kill = $pid[0];
> if ($p == $to_kill){
> $to_kill = $pid[1];
> }
> kill 15, $to_kill;
> die "goodbye cruel world\n";
> }
What if the thing waitpid returns is neither $pid[0] or $pid[1]?
> I could then use the library as follows:
>
> package main;
> sub main
> {
> my $o1 = obj->new(name=> 'o1');
> my $o2 = obj->new(name=> 'o2');
>
> eval {$o1->action();};
> if ($@){
> print "o1 killed\n";
> }
What if one of the processes from $o2 dies while in the middle of
$o1->action? What is the desired action?
> eval {$o2->action();};
> if ($@){
> print "o2 killed\n";
> }
> }
>
> main();
> 1;
>
> My problem is that I don't know how to call the 'watch' function
I don't think that there is any right way to call your existing watch
function. You need to re-arrange it.
>
> . I could call it in a CHLD sig handler, but in this case I do not
> know which object "generates" the CHLD signal.
You need a global (or widely-scoped lexical) hash that records the pids
that are started as keys, and the object that started it (or maybe some
kind of closure) as values. Then in a subroutine which is triggered by
SIGCHLD (or some other way), you would call waitpid, get the return value,
and look it up in the global hash to see what object you are in.
my $kid;
while (($kid = waitpid(-1, WNOHANG)) >0) {
die "Someone is spawning children ($kid) without telling me!"
unless exists $global_pid{$kid};
my $object = delete $global_pid{$kid};
if ($object->action_pending()) {
# action is pending on this action, so die to get out of it
die "Something went wrong with the object you are trying to use"
} else {
# no object pending, don't die until next time this object is used.
$object->hosed(1);
};
};
> In addtion, the method
> is very intrusive because it requires the signal handler declaration
> in the main module.
Not all situations can be handled in a nice encapsulated manner. For Perl,
at least, this is one of those situations. I don't think you will find any
non-intrusive way to do this.
> . I could declare a thread supervision per object (adding the line
> threads->new(\&watch, @pid)->detach(); in the obj::new constructor)
> but this does not run (message 'thread failed to start: goodbye cruel
> world')
Oh ick. Management of threading and forking are both bad enough on their
own. Mixing them is just that much worse.
Xho
--
-------------------- http://NewsReader.Com/ --------------------
Usenet Newsgroup Service $9.95/Month 30GB
------------------------------
Date: Fri, 11 May 2007 10:47:46 -0400
From: "Seth Brundle" <brundlefly76@hotmail.com>
Subject: Solve a statistics problem
Message-Id: <46448214$0$24247$8d2e0cab@news.usenetbinaries.com>
Say I have a hash with peoples names and a quality score, like their free
throw percentage.
Mathematically what is the most accurate way to divide the list into the two
most balanced teams?
Obviously you could do something simple like alternate in descending order,
but this isnt guaranteed to produce the most accurate result.
Ideally, I would like to be able to balance based on the mean, median, or
both.
Code isnt necessary but of course appreciated - but if you have a link to
the fundementals of solving such a problem thats fine to - I want to learn
to do it for myself.
------------------------------
Date: 11 May 2007 08:00:54 -0700
From: Paul Lalli <mritty@gmail.com>
Subject: Re: Solve a statistics problem
Message-Id: <1178895654.115586.182150@e65g2000hsc.googlegroups.com>
On May 11, 10:47 am, "Seth Brundle" <brundlefl...@hotmail.com> wrote:
> Say I have a hash with peoples names and a quality score, like their free
> throw percentage.
>
> Mathematically what is the most accurate way to divide the list into the two
> most balanced teams?
This question has nothing to do with Perl. It would be the same
question regardless of what language you're using to implment your
solution. You're asking a mathematics question. You're more likely
to get good answers in a group that discusses mathematics.
Paul Lalli
------------------------------
Date: Fri, 11 May 2007 10:07:44 -0500
From: Ignoramus6365 <ignoramus6365@NOSPAM.6365.invalid>
Subject: Re: Solve a statistics problem
Message-Id: <OIGdnczs_OxdG9nbnZ2dnUVZ_oPinZ2d@giganews.com>
On Fri, 11 May 2007 10:47:46 -0400, Seth Brundle <brundlefly76@hotmail.com> wrote:
> Say I have a hash with peoples names and a quality score, like their free
> throw percentage.
>
> Mathematically what is the most accurate way to divide the list into the two
> most balanced teams?
What does balanced mean exactly. Does it mean that you have to come
with a division so that the average score is closest? Or something
else?
Unless you have gross outliers, you will probably do well by sorting
the list by score, then you would take (unshift) pairs of people with
close scores (that is, take pair of persons 1 and 2 (two worst
scorers), then 3 and 4, then 5 and 6, and so on) etc. For every pair,
decide on who goes to which team on a randomized basis.
I hope that you have an even number of people. :)
That would probably do a good job in a great majority of cases.
i
> Obviously you could do something simple like alternate in descending order,
> but this isnt guaranteed to produce the most accurate result.
>
> Ideally, I would like to be able to balance based on the mean, median, or
> both.
>
> Code isnt necessary but of course appreciated - but if you have a link to
> the fundementals of solving such a problem thats fine to - I want to learn
> to do it for myself.
>
>
>
------------------------------
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 426
**************************************