[29443] in Perl-Users-Digest
Perl-Users Digest, Issue: 687 Volume: 11
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Jul 26 21:14:26 2007
Date: Thu, 26 Jul 2007 18:14:16 -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 Thu, 26 Jul 2007 Volume: 11 Number: 687
Today's topics:
Re: match string by re using some pattern <frytaz@gmail.com>
Re: match string by re using some pattern <mgjv@tradingpost.com.au>
Re: Math <hjp-usenet2@hjp.at>
Objects/Structures in Perl <olson_ord@yahoo.it>
Re: Objects/Structures in Perl <kkeller-usenet@wombat.san-francisco.ca.us>
Re: Objects/Structures in Perl <tadmc@seesig.invalid>
Re: Objects/Structures in Perl (Jens Thoms Toerring)
Re: pid from startet process (Douglas Wells)
standard setup for scripts <tom_spam@removethis-tabsoftwaresystems.com>
Re: standard setup for scripts <noreply@gunnar.cc>
String::CRC crc function returns incorrect result, why? <none@none.c0m>
Using backticks in forked child deoquinn@yahoo.com
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Thu, 26 Jul 2007 18:49:35 -0000
From: "frytaz@gmail.com" <frytaz@gmail.com>
Subject: Re: match string by re using some pattern
Message-Id: <1185475775.461655.101300@57g2000hsv.googlegroups.com>
On Jul 26, 12:00 pm, Matt Madrid <admiral...@gmail.com> wrote:
> fry...@gmail.com wrote:
>
> > OK, I'll try to explain it
>
> > for instance we parse http web page
>
> > $line = "section BOOKS - title SOME_BOOK_TITLE - price 20";
> [snip]
>
> > now we try to parse other page where
>
> > $line = "title CD_TITLE - price 50 - section MUSIC";
>
> [snip]
>
> > in this example, need to put different order of section,title,price
>
> I'm a little lost trying to figure out what you want to do also, but I'm
> going to guess that you want to extract the title, price, and section from
> each line, no matter what order they are in.
>
> Continuing on with what Anno showed you earlier, how about something like this:
>
> ---------------------------------------------------------------
> use strict;
> use warnings;
> #use Data::Dumper;
>
> my @items;
> while ( <DATA> ) {
> my %hash = /(section|title|price)\s+?(.+?)\s*?[-\n]/g;
> push(@items,\%hash) if keys(%hash);}
>
> #print Dumper(\@items);
>
> #Now you have a list of items, each of which is a hash ref
> #that you can access to grab the info:
>
> foreach (@items) {
> my ($title, $price, $section) = @{$_}{'title','price','section'};
> print
> "Title: '$title'\n".
> "Price: '$price'\n".
> "Section: '$section'\n\n";
>
> }
>
> __DATA__
> section BOOKS - title Green Eggs and Ham - price 6.95
> price 6.95 - section BOOKS - title The Cat In The Hat
>
> ---------------------------------------------------------------
>
> Matt M.
I'm up to create script which will listen to irc channel messages, and
then log three values Title, Price, Section but only msg which will
match defined regex like
$msg = 'Some MyTitleToLog price blah text MyPriceToLog with some text
MySectionToLog-';
$pattern = 'Some #TITLE# price blah text #PRICE# with some text
#SECTION#-';
then after match ill have it in $title $price $section or in array,
#$title -> MyTitleToLog
#$price -> MyPriceToLog
#section -> MySectionToLog
Patterns are stored in local file which I'm reading first in script,
and when $msg changes and mixup Title,Price,Section it will try other
pattern to match looking by irc nick
------------------------------
Date: Fri, 27 Jul 2007 07:29:42 +1000
From: Martien verbruggen <mgjv@tradingpost.com.au>
Subject: Re: match string by re using some pattern
Message-Id: <slrnfai4i6.iur.mgjv@martien.heliotrope.home>
On Thu, 26 Jul 2007 06:27:53 +0200,
Gunnar Hjalmarsson <noreply@gunnar.cc> wrote:
> Martien verbruggen wrote:
>>
>> my @lines = (
>> "section BOOKS - title SOME_BOOK_TITLE - price 20",
>> "title CD_TITLE - price 50 - section MUSIC",
>> "price 3 - title BARF BANANA - section RANDOM",
>> );
>>
>> my $kv_pattern = qr/(title|price|section) (.+?)/;
>>
>> for my $line (@lines)
>> {
>> print "$line\n";
>> my %kv = $line =~ /$kv_pattern - $kv_pattern - $kv_pattern/;
>> while (my ($key, $value) = each %kv)
>> {
>> print "\t$key -> $value\n";
>> }
>> }
>
> Did you run it?
I did, but I didn't study the output well enough
One line change should fix the problem you spotted.
my %kv = $line =~ /^$kv_pattern - $kv_pattern - $kv_pattern$/;
Sorry,
Martien
--
|
Martien Verbruggen | There is no reason anyone would want a
| computer in their home. -- Ken Olson,
| president DEC, 1977
------------------------------
Date: Thu, 26 Jul 2007 20:37:29 +0200
From: "Peter J. Holzer" <hjp-usenet2@hjp.at>
Subject: Re: Math
Message-Id: <slrnfahqf9.i1m.hjp-usenet2@zeno.hjp.at>
On 2007-07-23 17:52, Brian Blackmore <blb8@po.cwru.edu> wrote:
> Ilya Zakharevich <nospam-abuse@ilyaz.org> wrote:
>> For some unfathomable reasons, Perl uses non-invertible transformations
>> between strings and numbers. So if your handling of numbers involves
>> converting them to strings, then back, the precision will be lost.
>
> Yes, but I would question which programming languages don't suffer
> from this behavior?
I don't know. Which does? C certainly doesn't (although specific
implementations might).
> As is mentioned by perlnumber, converting from floating point to
> string is performed by the C compiler, whence Perl is at the mercy of
> the system on which it was compiled.
The glibc has no problem in this regard, AFAICT.
> Moreover, I must admit a bit of childish moronicity here in claiming
> that I know of no language whatsoever that stores floats with infinite
> precision, whence string conversion is always faulty.
Nope. Converting a binary number of a given precision to decimal and
back to binary is always possible without loss[0]. The problem seems to
be that perl uses only 15 decimal digits, while it would need 16 to
cover the 53 bits of mantissa (I think 16 should be enough, but I
haven't considered all cases - maybe there are some where 17 are
required).
> Indeed, I was also thinking of something simple like 1/3, but have
> you an example of a language where "1/3"=1/3? Or are there so many
> that I'm just being dim?
That's a completely different problem. 1/3 cannot be precisely
represented in binary, so the question whether it could be converted to
decimal and back is moot. The closest approximation to 1/3 which can be
represented in a 64 bit FP number
(0.333333333333333314829616256247390992939472198486328125) can be
converted to decimal and back without loss of precision.
hp
[0] In fact that's true for any two integral bases.
--
_ | Peter J. Holzer | I know I'd be respectful of a pirate
|_|_) | Sysadmin WSR | with an emu on his shoulder.
| | | hjp@hjp.at |
__/ | http://www.hjp.at/ | -- Sam in "Freefall"
------------------------------
Date: Thu, 26 Jul 2007 21:00:34 -0000
From: "O. Olson" <olson_ord@yahoo.it>
Subject: Objects/Structures in Perl
Message-Id: <1185483634.900208.65420@w3g2000hsg.googlegroups.com>
Hi,
I am for most part familiar C++/Java programming - but not much with
Perl. I am trying to figure out if I can use C style structures in
Perl - they are not classes per se - but sort of similar.
In the following code - which is part of a larger program - I tried
to group the hours, minutes and seconds of time into a combined data
structure. However once I set the current time ($curr_time) - the next
midnight time ($next_midnight) gets changed. Can anyone guess why??
As I said I am not much into Perl - so I might be doing something
obviously wrong.
-------------------------------------------------------------------
use warnings;
use strict;
# Declaration of a data structure that would hold a single line or
record of the file
# This would ensure that the file would never remain open if the
program exits prematurely
my $time = {
HOUR => my $hour,
MINUTE => my $minute,
SECOND => my $second
};
# Defining two variables of the type time
my $curr_time = $time; #Contains the hour, minute, second
my $next_midnight = $time; #Contains the hour, minute, second
# Setting the Next Midnight Time
($next_midnight->{HOUR}, $next_midnight->{MINUTE}, $next_midnight-
>{SECOND}) = (23, 59, 58);
print "Next Midnight Time: "; &printTime($next_midnight); print "\n";
# Setting the current time
($curr_time->{SECOND}, $curr_time->{MINUTE}, $curr_time->{HOUR}) =
localtime();
print "curr_time Time: "; &printTime($curr_time); print "\n";
print "But now, Next Midnight Time: "; &printTime($next_midnight);
print "\n";
# This function would print the time variable passed on to it, without
adding a new line character to it
sub printTime()
{
# Declaring a temporary time variable
my $temp_time = $time;
$temp_time = $_[0];
print "$temp_time->{HOUR}:$temp_time->{MINUTE}:$temp_time-
>{SECOND}";
}
------------------------------------------------------------
Console Output:
Next Midnight Time: 23:59:58
curr_time Time: 22:50:12
But now, Next Midnight Time: 22:50:12
---------------------------------------------------------
Why did "Next Midnight Time" change?
Thanks to all who help,
O.O.
------------------------------
Date: Thu, 26 Jul 2007 14:48:25 -0700
From: Keith Keller <kkeller-usenet@wombat.san-francisco.ca.us>
Subject: Re: Objects/Structures in Perl
Message-Id: <aehnn4xp88.ln2@goaway.wombat.san-francisco.ca.us>
On 2007-07-26, O. Olson <olson_ord@yahoo.it> wrote:
>
> In the following code - which is part of a larger program - I tried
> to group the hours, minutes and seconds of time into a combined data
> structure. However once I set the current time ($curr_time) - the next
> midnight time ($next_midnight) gets changed. Can anyone guess why??
[snip]
> use warnings;
> use strict;
>
> # Declaration of a data structure that would hold a single line or
> record of the file
> # This would ensure that the file would never remain open if the
> program exits prematurely
>
> my $time = {
> HOUR => my $hour,
> MINUTE => my $minute,
> SECOND => my $second
> };
This isn't a declaration of a datatype, which you don't have to do
in Perl, this is (in theory) an actual assignment to $time. Assuming
that instead you had
my ($hour,$minute,$second)=(12,43,56);
my $time = {
HOUR => $hour,
MINUTE => $minute,
SECOND => $second
};
then $time->{HOUR} would be 12. It's important to note that $time is
now a hash reference.
> # Defining two variables of the type time
> my $curr_time = $time; #Contains the hour, minute, second
> my $next_midnight = $time; #Contains the hour, minute, second
And because $time is a hashref, $curr_time and $next_midnight are both
hashrefs, and all three point to the same hash. So $curr_time->{HOUR}
is 12, as well as $next_midnight->{HOUR}.
> # Setting the Next Midnight Time
> ($next_midnight->{HOUR}, $next_midnight->{MINUTE}, $next_midnight-
>>{SECOND}) = (23, 59, 58);
> print "Next Midnight Time: "; &printTime($next_midnight); print "\n";
And therefore, modifying $next_midnight modifies $time and $curr_time.
(Strictly speaking, you're modifying the hash to which $next_midnight
points; since all three point to the same hash, you're ''modifying'' the
other two hashrefs too.)
It's probably easier to simply create each hashref the way you want it:
my $curr_time={
HOUR => 1,
MINUTE => 2,
SECOND => 3,
};
my $next_midnight={
HOUR => 4,
MINUTE => 5,
SECOND => 6,
};
Some more unrelated comments:
> # This function would print the time variable passed on to it, without
> adding a new line character to it
> sub printTime()
You have (), which strictly speaking defines printTime as a function
that takes no arguments. You don't see any errors because calling it
like you do above (&printTime($next_midnight)) circumvents prototypes.
You should probably leave out both the () on the sub definition, and the
& on function calls.
See perldoc perlreftut and perldoc perldsc for some more pointers.
--keith
--
kkeller-usenet@wombat.san-francisco.ca.us
(try just my userid to email me)
AOLSFAQ=http://www.therockgarden.ca/aolsfaq.txt
see X- headers for PGP signature information
------------------------------
Date: Thu, 26 Jul 2007 17:40:14 -0500
From: Tad McClellan <tadmc@seesig.invalid>
Subject: Re: Objects/Structures in Perl
Message-Id: <slrnfai8me.fms.tadmc@tadmc30.sbcglobal.net>
O. Olson <olson_ord@yahoo.it> wrote:
> I am trying to figure out if I can use C style structures in
> Perl
perldoc -q struct
How can I make the Perl equivalent of a C structure/C++ class/hash or
array of hashes or arrays?
--
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"
------------------------------
Date: 27 Jul 2007 00:19:59 GMT
From: jt@toerring.de (Jens Thoms Toerring)
Subject: Re: Objects/Structures in Perl
Message-Id: <5gss1fF3i9v53U1@mid.uni-berlin.de>
O. Olson <olson_ord@yahoo.it> wrote:
> I am for most part familiar C++/Java programming - but not much with
> Perl. I am trying to figure out if I can use C style structures in
> Perl - they are not classes per se - but sort of similar.
There's the one problem that Perl is neither C++ (or C) nor Java and
it doesn't have C style structures...
> In the following code - which is part of a larger program - I tried
> to group the hours, minutes and seconds of time into a combined data
> structure. However once I set the current time ($curr_time) - the next
> midnight time ($next_midnight) gets changed. Can anyone guess why??
> As I said I am not much into Perl - so I might be doing something
> obviously wrong.
> -------------------------------------------------------------------
> use warnings;
> use strict;
> # Declaration of a data structure that would hold a single line or
> record of the file
> # This would ensure that the file would never remain open if the
> program exits prematurely
> my $time = {
> HOUR => my $hour,
> MINUTE => my $minute,
> SECOND => my $second
> };
> # Defining two variables of the type time
> my $curr_time = $time; #Contains the hour, minute, second
> my $next_midnight = $time; #Contains the hour, minute, second
> # Setting the Next Midnight Time
> ($next_midnight->{HOUR}, $next_midnight->{MINUTE}, $next_midnight-
> >{SECOND}) = (23, 59, 58);
> print "Next Midnight Time: "; &printTime($next_midnight); print "\n";
> # Setting the current time
> ($curr_time->{SECOND}, $curr_time->{MINUTE}, $curr_time->{HOUR}) =
> localtime();
> print "curr_time Time: "; &printTime($curr_time); print "\n";
> print "But now, Next Midnight Time: "; &printTime($next_midnight);
> print "\n";
> # This function would print the time variable passed on to it, without
> adding a new line character to it
> sub printTime()
> {
> # Declaring a temporary time variable
> my $temp_time = $time;
> $temp_time = $_[0];
> print "$temp_time->{HOUR}:$temp_time->{MINUTE}:$temp_time-
> >{SECOND}";
> }
> ------------------------------------------------------------
> Console Output:
> Next Midnight Time: 23:59:58
> curr_time Time: 22:50:12
> But now, Next Midnight Time: 22:50:12
> ---------------------------------------------------------
> Why did "Next Midnight Time" change?
I can't answer this queston - my question is how you did get that
output at all since (for several reasons) your above code isn't
valid Perl?
I guess you need to free yourself at least a bit of your C++/Java
background and use instead what Perl gives you. While there are
many ways to do it, my first approach would probably be to create a
package for times like the following (with a bit of code at the start
that uses the package and outputs something similar to what you
posted):
------8<-------------------------------------------------------#!/usr/bin/perl
#!/usr/bin/perl
use strict;
use warnings;
my $current_time = new MyTime( );
my $next_midnight = new $current_time( 23, 59, 58 );
print "Next Midnight Time: " . $next_midnight->as_text . "\n" .
"curr_time Time: " . $current_time->as_text . "\n",
"But now, Next Midnight Time: " . $next_midnight->as_text . "\n";
package MyTime;
=pod
=head1 METHODS
=over 4
=item new()
new() can be called with 0 to 3 arguments: if there is none the new
object is initialized to the current (local) time, otherwise the
first argument is taken to be the hour, the second to be the minute
and the third as the second. Missing arguments are assumed to be 0.
=cut
sub new {
my $inv = shift;
my $class = ref( $inv ) || $inv;
die "Too many arguments\n" unless @_ <=3;
my $self;
if ( @_ == 0 ) { # no arguments
my @time = localtime( );
$self = { hour => $time[ 2 ],
minute => $time[ 1 ],
second => $time[ 0 ] };
} else {
$self = { hour => $_[ 0 ],
minute => $_[ 1 ] || 0,
second => $_[ 2 ] || 0 };
}
return bless $self, $class;
}
=pod
=item as_text()
Returns a string of the time the object represents in "hh:mm:ss" format.
=cut
sub as_text {
my $self = shift;
return sprintf "%02d:%02d:%02d",
$self->{ hour }, $self->{ minute }, $self->{ second };
}
1;
------8<-------------------------------------------------------
That way you can create new objects (similar to C++ or Java)
representing times and print them. Adding methods that return
or change the hour, minute or second is simple, e.g. for getting
or setting the hour you would just need e.g.
sub hour {
my $self = shift;
$self->{ hour } = shift if exists $_[ 0 ];
return $self->{ hour };
}
Of course, this MyTime package would need quite a bit of error
checking (what happens when you pass it non-numeric or negative
arguments or hours above 23 or minutes or seconds above 59?)
but I hope it gives you an idea of how you could do it in Perl.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
------------------------------
Date: Thu, 26 Jul 2007 18:57:50 -0400 (EDT)
From: see@signature.invalid (Douglas Wells)
Subject: Re: pid from startet process
Message-Id: <f8b8te$1trb$1@flame.contek.com>
In article <slrnfahnt5.i1m.hjp-usenet2@zeno.hjp.at>,
"Peter J. Holzer" <hjp-usenet2@hjp.at> writes:
> On 2007-07-19 22:28, Douglas Wells <see@signature.invalid> wrote:
> > (And in response to another comment in this thread, the PID of
> > child will almost certainly not be the shell's PID plus 1. Any
> > system that does that presents a major security risk and should
> > be trashed immediately -- because PIDs would then be guessable.)
>
> PIDs are guessable on the majority of unix systems (the only exceptions
> I know are some BSD variants) - so this is something the average unix
> programmer expects.
Yes, elsewhere in this thread, I acknowledged that I made a wrong
declaration about "most" POSIX-like system: Many of them do
generate new candidates for PIDs by incrementing a counter. I
have not, however, yielded on the claim of a security threat posed
by this algorithm. Instead, I supplied a scenario, based on
historical security incidents, that posed a threat in the presence
of this algorithm.
> OTOH, a random pid is something the average unix programmer does not
> expect - which may lead to a different class of (possibly
> security-critical) errors.
I'm sorry, but I find that (the security-critical error possibility)
preposterous. Can you provide a scenario that both leads to correct
behavior in the presence of the incrementing PID algorithm and to
the presence of a security threat in its absence?
In fact, I'd like to hear of a scenario that leads to non-probabilistic
correct behavior in the presence of an application-level program
that predicts future PIDs based on any algorithm. Can you provide
one?
I can imagine a frazzled human debugging a multi-process program,
operating in a benign environment, and choosing to attach the
the "next" PID based on a mental calculation. But, I fail to
understand how that could work reasonably in a deployed system.
It appears to me any user-level algorithm for predicting the "next"
PID, such as adding one to the PID of the current process, faces
several difficulties:
- The system could well have created a non-related process with
the "next" PID in the meanwhile.
- The current sequence may have reached the maximum PID value and
wrap around. Neither the maximum value nor the initial value
after wrap-around is specified by the POSIX standard (nor by
the Linux standard, which seems to defer to POSIX in this
instance).
- Even if neither of those events has occurred, the "next" PID
might not be usable due to the existence of a long-lived process
with that ID, and the standard's requirement that PIDs be
temporally unique.
- Even if there isn't an existing process with the same PID,
that PID value might not be usable due to the standard's
"Process ID Reuse" prohibition on reuse of process group ids.
Can you offer an user-level algorithm that alleviates the effect
of those problems?
Also, do you actually know of any interesting applications that
would significantly benefit by knowing the PID of a process that
has yet to be created?
> hp
- dmw
--
. Douglas Wells . Connection Technologies .
. Internet: -sp9804- -at - contek.com- .
------------------------------
Date: Thu, 26 Jul 2007 19:44:39 -0400
From: Tom Bolick <tom_spam@removethis-tabsoftwaresystems.com>
Subject: standard setup for scripts
Message-Id: <xlaqi.5656$WN1.4139@bignews2.bellsouth.net>
All of my perl scripts have this at the top:
-------
#!/usr/bin/perl
$IS_WEBSITE = (-e "/home/userme/lib/site_perl");
if ($IS_WEBSITE){
use lib "/home/userme/lib/site_perl";
$ENV{HTML_TEMPLATE_ROOT}='/home/userme/www/project1/online/eng';
}
else {
$ENV{HTML_TEMPLATE_ROOT}='/WWWSites/client1/project1/online/eng';
}
$ENV{HEAD_BASE}='../project1/online/eng/';
use strict;
use CGI;
use CGI::Carp qw(fatalsToBrowser set_message);
-----------
Is there a way to put this in a single setup file that all scripts call,
like setup.pl?
As you can see, I check to see if I am running on my production server,
or my development machine and change some variables and libraries
accordingly. Anyone have any better suggestions?
Tom...
------------------------------
Date: Fri, 27 Jul 2007 02:10:40 +0200
From: Gunnar Hjalmarsson <noreply@gunnar.cc>
Subject: Re: standard setup for scripts
Message-Id: <5gsrmdF3in3omU1@mid.individual.net>
Tom Bolick wrote:
> All of my perl scripts have this at the top:
> -------
> #!/usr/bin/perl
>
> $IS_WEBSITE = (-e "/home/userme/lib/site_perl");
>
> if ($IS_WEBSITE){
> use lib "/home/userme/lib/site_perl";
It should be noted that the 'use lib' statement is always executed,
since it happens at compile time. OTOH, even if that path is added to
@INC unnecessarily, i.e. also when it does not exist, it won't hurt.
> $ENV{HTML_TEMPLATE_ROOT}='/home/userme/www/project1/online/eng';
> }
> else {
> $ENV{HTML_TEMPLATE_ROOT}='/WWWSites/client1/project1/online/eng';
> }
> $ENV{HEAD_BASE}='../project1/online/eng/';
>
> use strict;
> use CGI;
> use CGI::Carp qw(fatalsToBrowser set_message);
> -----------
>
> Is there a way to put this in a single setup file that all scripts call,
> like setup.pl?
Guess you could put all but the first line in a separate file and call
it like:
BEGIN { do 'setup.pl' }
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
------------------------------
Date: Thu, 26 Jul 2007 23:02:25 +0100
From: `Zidane Tribal <none@none.c0m>
Subject: String::CRC crc function returns incorrect result, why?
Message-Id: <KR8qi.137295$764.71@newsfe12.ams>
it would appear that using the command 'crc("data")' from the String::CRC
returns incorrect results (although, they are at least consistently
incorrect).
for example, this script.....
#!/usr/bin/perl -w
use strict;
use String::CRC;
print "crc: " . crc($ARGV[0]) . " " . length($ARGV[0]) . "\n";
produces this output:
zidane@bluemist:~/ps2/dev/crccheck$ ./crctest.pl 12345
crc: 3817467633 5
zidane@bluemist:~/ps2/dev/crccheck$
whereas this command:
zidane@bluemist:~/ps2/dev/crccheck$ echo -n "12345" | cksum
3288622155 5
zidane@bluemist:~/ps2/dev/crccheck$
produces a different crc value.
this is also true using String::CRC32, DIGEST::CRC and DIGEST::CRC32 (using
the command line commands cksum and crc32 to create respective crc and
crc32 values to test against)
my query is simple.... why is this? although the values are different,
they are consistently different (i.e. the same result returned with each
call given the same data). can anyone explain what i am doing wrong?
`Zidane.
--
You dont need a reason to help people. `Zidane Tribal.
------------------------------
Date: Thu, 26 Jul 2007 16:38:38 -0700
From: deoquinn@yahoo.com
Subject: Using backticks in forked child
Message-Id: <1185493118.785085.190290@l70g2000hse.googlegroups.com>
Hello all, I have a a need to use backticks in a forked child while
running many simultaneous children (on Windows). This is a pinging
application, so, I am pinging multiple hosts and capturing their ping
response time as shown below.... The problem is that I can *only* get
this to work if I move the 'child' code to another script and then
'exec(....)' that script, which is turning out to be *very* expensive
and slow... If I run it as coded, it hangs after the first (sometimes
first couple of) forks. Do I need to do something with STDIN/STDOUT
(or something else) in the child here? I have tried several different
ways of doing this (including using Net::Ping ( with external protocol
and HiRes ) but it didn't perform very well nor behave like I wanted -
plus, I will be running this on multiple systems and do not want to
have to install more modules everywhere and keep them up to date, so,
I'd like to leave that out)...
So... The question is... How do the system calls happen in the
forked children and why is such a call hanging the script? The
platform is Windows Server 2003 and the perl vers is 5.8.8 Build 820.
Thanks to any responders....
foreach $host ( sort { uc($a) cmp uc($b) } keys %hosts ) {
my $pid;
# throttle back the spawning to limit impact on system
if ( $throttle++ > 20 ) { sleep 5; $throttle = 0; }
FORK: {
if ( $pid = fork ) {
# Parent
# Harvest a few finished children if existent....
waitpid(-1,WNOHANG);
next; # go get next host and fork again...
}
elsif ( defined $pid ) {
# Child
my $avg = -1;
for ( my $i = 1; $i < 4 && $avg == -1; $i++ ) {
$wait = $i*1000;
foreach ( reverse (`ping -w 1000 -n 1 $host`) )
{ ###### BACKTICKS HERE
last if $avg != -1 || $? > 0;
# Get the avg ping response time only - implied ping
failure is $avg is not changed from -1
if ( m/Average\s=\s/ ) { ( $avg = $_ ) =~ s/^.*?Average\s=
\s(\d+).*\n*$/$1/ }
}
}
print "\Child: Average $host - $avg ms\n";
}
elsif ( $! == EAGAIN ) {
# Sleep a little and Harvest orphaned children before retrying
fork....\n";
sleep 5;
wait();
redo FORK;
}
else { die "Unrecoverable Fork Error: $!" }
} # end FORK Label
} # end FOREACH loop
exit;
------------------------------
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 687
**************************************