[8737] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 2354 Volume: 8

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Apr 17 18:07:16 1998

Date: Fri, 17 Apr 98 15:00:28 -0700
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, 17 Apr 1998     Volume: 8 Number: 2354

Today's topics:
    Re: array of matches in s/// (Charles DeRykus)
    Re: Attempt to speed up rand() (Jamie McCarthy)
    Re: Attempt to speed up rand() (Mark Waterous)
        Chicago-based Perl/Cgi Ace Wanted <mvelasco@new2000.com>
    Re: considerations for global variables? (Ken Williams)
    Re: considerations for global variables? <david.x.corcoran@boeing.com>
        Excel via cgi <peter###@uhu.com>
    Re: HELP: exec($prog) or die "exec failed"; (Charles DeRykus)
        Help: Novice Question .pm -> .html <tkho@technologist.com>
        how can I get commands to display? <joe@garage.com>
    Re: How to get only 2 decimal notation? <lr@hpl.hp.com>
    Re: How to insert a \n each... <lr@hpl.hp.com>
    Re: how to remove blanks? <zenin@archive.rhps.org>
    Re: Multi-tasking/threading <zenin@archive.rhps.org>
        new syntax for tied variables? (Ken Williams)
        OOPerl/References Misunderstanding (Ed.Q.Bridges)
    Re: order of declaration - my, local, anonymous sub <ebohlman@netcom.com>
    Re: perl on windows <sowmaster@juicepigs.com>
        perl_eval_pv: how to catch errors? igor@everyware.com
    Re: Problems with 'wait' under perl5.004 (Rob Pinelli)
        Proplem with perl script (I'm new to perl) <toby@he-net.demon.co.uk>
    Re: reading values from multi-select list <Glenn.J.Schworak@state.or.us>
    Re: Send Message to Event Viewer <david.x.corcoran@boeing.com>
    Re: Snobby news group (Stuart McDow)
    Re: Snobby news group <sowmaster@juicepigs.com>
    Re: Snobby news group (Greg Bacon)
    Re: Undef vs. Empty Anon Array ([]) as subroutine param (Stuart McDow)
        Digest Administrivia (Last modified: 8 Mar 97) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Thu, 16 Apr 1998 19:52:35 GMT
From: ced@bcstec.ca.boeing.com (Charles DeRykus)
Subject: Re: array of matches in s///
Message-Id: <ErIv7n.4CA@news.boeing.com>

In article <3536adb0.25241937@news.tornado.be>,
Bart Lateur <bart.mediamind@tornado.be> wrote:
>Is it possible to store matches inside s/// into an array? I think not.
>
>Ex. in a translation scheme (one phrase):
>
>	s/^It is now (\d+) to (\d+)\./Il est $2 heures moins $1./;
>
>Of course I want to be able to apply more than one translation to a
>text, so it would be nice to store the English phrases as keys of a
>hash, with the translated phrases as the value. 
>
>This translation scheme doesn't work:
>
>	$key = 'It is now (\d+) to (\d+)\.';
>	$value{}$key} = 'Il est $2 heures moins $1.';
>	s/^$key/$translate{$key}/;
>
>because there won't be any variable interpolation: $1 and $2 will still
>be there, literally.
>
>'eval' is out of the question, because the phrases are stored into an
>external data file. Tainted code is something I don't regard highly, and
>I only want to substitute actual matches, not just any variable.
>
>I'm thinking about putting this into a sub:
>
>       s/$key/&interpolate($translate{$key})/e;
>
>Interpolation usually involves uses regex substitution (it does in my
>case).This masks the matched values I want to insert, so I must preserve
>them into an array or something. I don't know beforehand how many
>matches there are, so I think this is very messy:
>
>	sub interpolate {
>		@match = ($1,$2,$3,$4,$5);
>		...
>	}
>
>I really ought to pass the matches as parameters to the sub:
>
>       s/$key/&interpolate($translate{$key}, $1, $2, $3, $4, $5)/e;
>
>Just as messy.
>
>Am I missing a better solution? Can I pass the array of matches to a
>sub? Is this something actually worth wishing for?
>

Could you substitute format strings in the key values 
or did something get mangled in translation... :) 



  $translate{$key} = 'Il est %s heures moins %s.'; 
  if (my @matches = /^$key/) {
     s/^$key/sprintf "$translate{$key}", @matches/e;
  }



HTH,
--
Charles DeRykus


------------------------------

Date: Fri, 17 Apr 1998 16:17:19 -0400
From: jamie@mccarthy.org (Jamie McCarthy)
Subject: Re: Attempt to speed up rand()
Message-Id: <jamie-1704981617210001@clmxmi133074.voyager.net>

The line of code added below can't hurt, and might make the page
appear faster on a typical web browser.

mail@silas.hypermart.net wrote:

> #!/usr/local/bin/perl -w
> use diagnostics;
> use strict;


$| = 1; # disable buffering on STDOUT


> my $count = 2;
> my $page_load = int(rand($count));
> 
> print "Content-type: text/html\n\n";
> 
> open (FILE, "$page_load") || die "Couldn't open file [".$page_load."]
> Reason: $!"";
>   while (<FILE>) {
>    print "$_";
>   }
> close (FILE) || die "Couldn't close file [".$page_load."] Reason: $!";

Also, the quotes around $_ are unnecessary and might make you
think they're doing something, when they're not.  :-)  Even the
$_ itself is unnecessary, in fact.  Try just:

   print while <FILE>;

which is a clever and perfectly natural perl idiom.
-- 
 webmaster: http://www.holocaust-history.org/     Jamie McCarthy
    fan of: http://www.nizkor.org/                jamie@mccarthy.org
                                           http://jamie.mccarthy.org/


------------------------------

Date: Fri, 17 Apr 1998 21:22:36 GMT
From: mail@silas.hypermart.net (Mark Waterous)
Subject: Re: Attempt to speed up rand()
Message-Id: <3537bb0b.16527122@news.bctel.ca>

On Fri, 17 Apr 1998 06:12:17 GMT, Tom Phoenix <rootbeer@teleport.com>
wrote:

>On Fri, 17 Apr 1998, Mark Waterous wrote:
>
>> 	What I am attempting to do now, though I don't know if it's
>> possible, is to speed up the process a bit. It delays for just over a
>> second before returning a page, and though this isn't too much, if it
>> can be gotten around, I would like to do it. 
>
>That's not rand's fault! That's just normal start-up time, and it sounds
>as if you want to cut that down. One way to reduce a Perl CGI script's
>start-up time (often to nearly zero) is to use Apache's mod_perl. Ask your
>webmaster to help you to do that. Good luck!

	Heh, I wasn't quite blaming it on rand()... okay, perhaps I
was. I had a brief glance at something to do with mod_perl at the
apacheweek.com site, so I suppose now I'll go back and take a look
again... :)



_________________________________
Mark Waterous - Silas Productions Online

"Your entrance to a world of information..."
                          http://silas.hypermart.net/


------------------------------

Date: Fri, 17 Apr 1998 16:19:25 -0500
From: "Michael Velasco" <mvelasco@new2000.com>
Subject: Chicago-based Perl/Cgi Ace Wanted
Message-Id: <6h8gvc$b5f$1@hirame.wwa.com>

I'm looking for a pretty hot Perl/CGI programmer based in the Chicago who's
looking for some steady project work.  Email me and let me know if you're
interested and we'll talk specifics.

Michael Velasco
mvelasco@new2000.com
www.new2000.com





------------------------------

Date: Fri, 17 Apr 1998 17:26:39 -0400
From: ken@forum.swarthmore.edu (Ken Williams)
Subject: Re: considerations for global variables?
Message-Id: <ken-1704981726390001@news.swarthmore.edu>

In article <3534D1C2.DC@flash.net>, dtbaker_@flash.net wrote:

>Andrew M. Langmead wrote:
>> 
>> Dan Baker <dtbaker_@flash.net> writes:
>> 
>> >I would like to learn more about the considerations and options for how
>> >to use "global" variables in perl scripts which are not in a single
>> >program.... i.e. a .html page may execute one script to create or modify
>> >some values which need to be used by a different script at a later time.
>> 
>> Your idea of "global variables" seems to differ from what most
>> programmers consider global variables.
>-------------
>well... that's why I put it in quotes. I couldn't think of a better way
>to put it. Perhaps a better way would be a "persistant variable". I
>expect that in my particular application I will need a stateless way to
>store variables to fake passing between perls scripts that are fired up
>as separate standalone sripts driven from an html "interface". The
>scripts can't be in a single process in this particular application. I
>think I'll need to write/read a text file...

Hi Dan,

The idea of using text files to store data is undoubtedly the simplest,
but if you really want to keep persistent real variables from one web hit
to the next, you should check out mod_perl - http://perl.apache.org/ .  I
use it, it's great.  

You can share variables across several running processes with the
IPC::Shareable module available on CPAN.  It puts the variables in shared
memory.  I've never used it but I know people who have.

Using mod_perl will take a while for you - you have to recompile your web
server and figure out how to adjust your thinking.  In the long run, I
think it's worth it, but consider yourself warned.


------------------------------

Date: Wed, 15 Apr 1998 20:25:30 GMT
From: David Corcoran <david.x.corcoran@boeing.com>
To: "Andrew M. Langmead" <aml@world.std.com>
Subject: Re: considerations for global variables?
Message-Id: <353517BA.3C56@boeing.com>

Andrew M. Langmead wrote:
> 
> Dan Baker <dtbaker_@flash.net> writes:
> 
> >I would like to learn more about the considerations and options for how
> >to use "global" variables in perl scripts which are not in a single
> >program.... i.e. a .html page may execute one script to create or modify
> >some values which need to be used by a different script at a later time.
> 
> Your idea of "global variables" seems to differ from what most
> programmers consider global variables.
> 
> A set of variables are exclusive to a single process. (an instance of
> an execution of a program.)
> 
> Offline storage, such as disk files, are a way to save data between
> instances of execution of a program and with care, between two
> simultaneous instances of an executing program.
> 
> --
> Andrew Langmead
see:
http://theory.uwinnipeg.ca/CPAN/data/Data-Dumper/README.html


------------------------------

Date: Fri, 17 Apr 1998 17:42:27 -0400
From: Peter Tapolyai <peter###@uhu.com>
Subject: Excel via cgi
Message-Id: <3537CCC2.1622@uhu.com>

I have to query an MS Excel Spreadsheet across the web.
I have the simplified core of the cgi below. However, this
query does not return the very first 'records' (or cell values)
or any text values either.
That is if I have:
	A	B
1	11	12
2	21	text
3	31	32
values in a spreadsheet, then all numberical values returned,
with the exception of A1 and B1 values in addition to the B2 'text'.
Column A's name is F1 and Column B is F2 through ODBC.

Any ideas what I am missing ?

use Win32::ODBC;
$DSN = "Excel";
$db = new Win32::ODBC($DSN);

&html_header;
print "Excel Data<br>\n";
print "<ol>\n";
$db->Sql("SELECT * FROM \"Sheet1\$\"");
while ($db->FetchRow()){
  %in = $db->DataHash();
  print " <li>", $in{F1}, " ", $in{F2}, "\n";
}
print "<\/ol>\n";
$db->Close();
&html_footer;

-- 



Remove ### from before replying

peter###@uhu.com
http://www.uhu.com/tinkershop/


------------------------------

Date: Thu, 16 Apr 1998 00:39:44 GMT
From: ced@bcstec.ca.boeing.com (Charles DeRykus)
Subject: Re: HELP: exec($prog) or die "exec failed";
Message-Id: <ErHDu8.FJE@news.boeing.com>

In article <3534E665.36B5A997@eq.gs.com>,
PETER SZWEDYK  <peter.szwedyk@eq.gs.com> wrote:
>When I waitpid for exec to finish, I  can check $? for child error, BUT
>WHAT  IF I DON'T waitpid?  In this case, $? is always 0, even if exec
>failed.
>
>HOW CAN I CATCH THE die "exec failed" back in the parent program?  I
>know that I could redirect STDERR in child to write to a file and then
>back in parent read in that file and parse for 'exec failed'.  IS THERE
>AN EASIER WAY???  Can I redirect the die "exec failed" streight to a
>string var in the parent process?
>
>Here is my script.  Thanks in advance!
>
>$exec_str = "load_data.pl";
>$fg_bg_indic = 'B';
>select (STDERR); $| = 1;
>select (STDOUT); $| = 1;
>
>FORK: {
>        if ($pid = fork)
>        {
>                if($fg_bg_indic eq 'B')
>                {
>                        print "not waiting...\n";
>                }
>                else
>                {
>                        print "waiting...\n";
>                        waitpid($pid,0);
>                }
>        }
>        elsif (defined $pid)
>        {
>                print "exec...\n";
>                exec ($exec_str) or die "exec failed: $!";
>                exit;
>        }
>        elsif ($! =~ /No more process/)
>        {
>                sleep 5;
>                redo FORK;
>        }
>        else
>        {
>                die "can't fork: $!\n";
>        }
>}
>print "OS ERRr: $!, CHILD ERR: $?\n";  #if child sent to background,
>
>

Other than something non-portable, you'll probably need pipe 
redirection, e.g.

  pipe(READER, WRITER);
  if ($pid = fork) {
     close(WRITER);
     @status = <READER>;
     ...
  } elsif (defined $pid) {
     close(READER);
     unless (exec $exec_str) {
         select((select(WRITE), $|++)[0]);
         print WRITE "exec failed: $!";
     }
     ...
  

You may want to re-direct stderr to the pipe handle too
to quiet the shell.
 

HTH,
--
Charles DeRykus


------------------------------

Date: Fri, 17 Apr 1998 14:23:42 -0700
From: Tommy <tkho@technologist.com>
Subject: Help: Novice Question .pm -> .html
Message-Id: <3537C85E.CE7F108C@technologist.com>

I have a novice question on how to turn the description of .pm to either
 .html or txt. I remember there is a perl script pm2html.pl (like
pod2html.pl), but I forget where I can get it.

Tommy Ho
tkho@technologist.com



------------------------------

Date: Fri, 17 Apr 1998 14:37:29 -0700
From: joes garage <joe@garage.com>
Subject: how can I get commands to display?
Message-Id: <3537CB99.2AD4@garage.com>

I looked at the FAQ and programming perl book and cannot find
what I am looking for.  I would like to display lines as they execute.

I am looking for the equiv of set -x in shell.
Does such a beast exist?


thanks
Ken


------------------------------

Date: Fri, 17 Apr 1998 14:02:38 -0700
From: "Larry Rosler" <lr@hpl.hp.com>
Subject: Re: How to get only 2 decimal notation?
Message-Id: <6h8g1j$7ci@hplntx.hpl.hp.com>

ppp-support wrote in message <3537B5E9.36216644@canelle.telecom.uqam.ca>...
>tony wrote:
>
>> > Huh?  Sprintf does round:
>> >
>> > perl -e 'print sprintf("%.2f\n", 1.249)'
>> > 1.25
>> > perl -e 'print sprintf("%.2f\n", 1.241)'
>> > 1.24
>
>sprintf looks nice but if i want a sub routine to take care of that
>rounding stuf??
>
>sub round
>{
>  my $value = $_[0];
>  my $precision = $_[1];
>  my $value;
>  ... # Do the rounding with the precision we want
>  return $value;
>}
>
>and then we could use smething like this:
>
>$value = (27/126)*100;
>$roundvalue = &round($value);
>
>So we can print out $roundvalue or do something else with it, like
>passing the rounded value to another routine etc..! Can it be more
>useful like this?
>
>Reni
>
sub round
{
  my ($value, $precision) = @_;  # A bit neater...
  ... # Do the rounding with the precision we want
  sprintf '%.*f', $precision,  $value;
# or:  sprintf "%.${precision}f", $value;
# or:  sprintf '%.' . $precision . 'f', $value;
}

Pick any of the "return" statements -- they all do the same thing.  If it
were me, I'd just use $_[0] and $_[1], but your way has mnemonic value.  As
a one-liner (without error-checking of the args):

sub round { sprintf "%.$_[1]f", $_[0]}

--
Larry Rosler
Hewlett-Packard Laboratories
lr@hpl.hp.com





------------------------------

Date: Fri, 17 Apr 1998 13:45:20 -0700
From: "Larry Rosler" <lr@hpl.hp.com>
Subject: Re: How to insert a \n each...
Message-Id: <6h8f11$748@hplntx.hpl.hp.com>

Phil Vuong wrote in message
<01bd69b2$108e5360$57b837cb@melcs10.gribbles.com.au>...
>
>
>> > LE CORRE (lecorre@magic.fr) wrote:
>> > : I tried $line=~ s/.{10}/\n/g; but it doesn't work.
>
>Try this :
>$line =~ s/.{10}/$&\\n/g ;
>
>PV


No.  Too many backslashes.  And $& is relatively inefficient.  The better
answer has already appeard in this group:

$line =~ s/(.{10})/$1\n/g ;

--
Larry Rosler
Hewlett-Packard Laboratories
lr@hpl.hp.com





------------------------------

Date: 17 Apr 1998 21:06:13 GMT
From: Zenin <zenin@archive.rhps.org>
Subject: Re: how to remove blanks?
Message-Id: <892847602.907082@thrush.omix.com>

Larry Rosler <lr@hpl.hp.com> wrote:
: Zenin wrote in message <892836055.73298@thrush.omix.com>...
	>snip<
: > $string =~ s/(?:^\s+|\s+$)//g;
:                         ^^^              ^
: I don't think these parentheses accomplish anything.

	Yes, they do.

: ("Don't capture the match that's not used anyway.")

	They perform needed grouping, and if you notice the details
	I don't capture anything at all.  See the perlre man page about
	the "(?:pattern)" modifier extension if you doubt this.

: > Benchmark: timing 100000 iterations of FAQ, EASIEST, ZENIN...
	>snip<
: Without your test string, it's difficult to reproduce or comment on these
: results.

	#!/usr/local/bin/perl
	use Benchmark;
	timethese 100000, {
	    EASIEST	=> sub {
	        $foo = "            string           ";
	        $foo =~ s/^\s*(.*?)\s*$/$1/;
	    },
	    TWO_PART => sub {
	        $foo = "            string           ";
	        $foo =~ s/^\s+//;
                $foo =~ s/\s+$//;
	    },
	    ZENIN => sub {
	        $foo = "            string           ";
                $foo =~ s/(?:^\s+|\s+$)//go;
	    }
	};

	__END__

	Enjoy. :-)


	>snip<
: $string =~ s/^\s*(.*\S)\s*$/$1/;

	Hmm, you assume (danger!) here that there even is non-whitespace
	data in the string.  You'll fail to remove whitespace on a simple
	"   " string.

: My benchmark results (usr time for 100000 iterations) if
: $string = "\t\t\txxx\t\t\t"; are

	Sorry, but for testing perl snips of code, time(1) is about
	the most inconsistent tool available.  This is why the Benchmark
	module is shipped standard.  See my test code above for example
	usage.

: EASIEST:      5.18
: FASTEST:     4.41
: TWO_PART: 6.00
: ZENIN:           5.92
:
: Obviously, YMMV.

	And without your code we can't reproduce your results either. :-)
	I'd advise recoding your test using the Benchmark module and see
	what turns up.  When using time(1), you're testing perl startup
	and system fork/exec costs much, much more then the perl run time
	algorithms.  I think you'll get *much* different and more accurate
	results using the Benchmark module.

	But the fact remains, it's all pretty academic unless you really
	need to worry about nano-seconds in which case you've got bigger
	problems. :-)

-- 
-Zenin
 zenin@archive.rhps.org


------------------------------

Date: 17 Apr 1998 21:10:12 GMT
From: Zenin <zenin@archive.rhps.org>
Subject: Re: Multi-tasking/threading
Message-Id: <892847841.399352@thrush.omix.com>

Russ Allbery <rra@stanford.edu> wrote:
: *nod*  And I'm looking forward to threads for easy implementation of an
: event loop using some of the techniques Malcolm has talked about,
: hopefully involving the ability to do safe asych signal handling.

	I gave up on perl signals so long ago I forgot about them actually
	expected to work under a threaded perl.  Yes, now that I remember
	that part I'm also looking forward to safe, working signals as
	well.  I don't even care about async (much), I just care about
	actually catching them without corrupting perl and thus causing
	random core dumps. :-)

-- 
-Zenin
 zenin@archive.rhps.org


------------------------------

Date: Fri, 17 Apr 1998 17:11:29 -0400
From: ken@forum.swarthmore.edu (Ken Williams)
Subject: new syntax for tied variables?
Message-Id: <ken-1704981711290001@news.swarthmore.edu>

Hi,

On lots of occasions I've wanted to do something like this to extend the
possibilities for extending the access to a hash:

#######################
package MyTie;

sub TIEHASH {
   ...
}

sub FETCH {
   ...
}

 ... more tying methods

sub extra_method {
   my $self = shift;
   ... do something
}

#######################
package main;

tie(%hash, 'MyTie');
$hash{one} = 'two';          # Regular access
%hash->extra_method("arg");  # Special access
#######################

Wouldn't that be fun?  It sure is more appealing to me than this:

 $obj = tie(%hash, 'MyTie');  # Yuck
 $hash{one} = 'two';          # Regular access
 $obj->extra_method("arg");   # Yuck!


Not to mention the untie() gotcha associated with this way.  

Wouldn't it be great?  (I assume some people will write about why it
wouldn't be great, and that's part of what I'd like to hear)


------------------------------

Date: Fri, 17 Apr 1998 20:58:01 GMT
From: fakeuser@fakemail.com (Ed.Q.Bridges)
Subject: OOPerl/References Misunderstanding
Message-Id: <3537b96e.283524005@news.spry.com>

below is a simple attempt at grasping perl's oo features.  it is a
"Question" class that takes a question and its possible answers
and then scans a datafile of answers that people have submitted and
builds a Question object that contains:
* the question
* all of its possible answers
* a count of the number of times each answer was selected
* the percentiles of each answer chosen.

when i instantiate a single instance of the question, it works fine.
when i try to create an array of question objects, and to access the
data structures of the objects it screws up.  if i'm just accessing a
scalar value (like the question) from the array of questions, it works
fine;  when it's an array or a hash, i get things like this
ARRAY(0x173d40).  

i recognize i'm not grasping the way that perl references and
dereferences objects and structures.  i'm coming from a C/C++
background when thinking about things like this, and i think i've a
mental block on how perl treats rthem.

i've broken up package main into two blocks:
THIS_WORKS which is the single instance of a Question; and
THIS_DOES_NOT_WORK which is the array of Questions.

the Question package/class follows package main.

any help would be greatly appreciated!!

please CC any postings to my email address.

thank you,
--ed.bridges--
eqbridges@cbs.com 

######################################################

#!/usr/bin/perl
use FileHandle;

package main;

$datafile = 'Test_data.dat';
die "Can't open $datafile: $!\n" 
    unless ($fh = new FileHandle "$datafile", "r");

THIS_WORKS:
{
    ## CONFIGURE & INSTANTIATE ONE QUESTION OBJECT
    $Index = 30;	    # Column number in row of data with answer
    $Qname = 'Q1';  # Question itself
    @ListOfAnswers = ( 'A', 'B', 'C' );
    $Q = new Question( $fh, $Qname, $Index, $#ListofAnswers+1,
@ListOfAnswers );

    ## PRINT OUT RESULTS
    print "GetQuestion is: " . $Q->GetQuestion() . "\n";
    
    @ans = $Q->GetAnswers;
    print "ans[0] is: " . $ans[0] . ", ";
    print "ans[1] is: " . $ans[1] . ", ";
    print "ans[2] is: " . $ans[2] . "\n";

    %res = $Q->GetResults();
    foreach ( @ans ) {	print "$_  is $res{$_}\n";    }

    %per = $Q->GetPercent();
    foreach ( @ans ) {	print "$_ is $per{$_}%\n";    }

    print "\n";
}

THIS_DOES_NOT_WORK:
{
    ## CONFIGURE & INSTANTIATE AN ARRAY OF QUESTION OBJECTS
    $Index = 28;    # Column number in row of data where answers begin
    @Qnames = ('Q1','Q2');     # Questions themselves
    @ListOfAnswers = ( ['A', 'B' ], ['A', 'B', 'C'] );
    
    for $i ( $[ .. $#Qnames ){
	$Questions[$i] = 
		new Question( $fh, $Qnames[$i], ($Index+$i),
			$#{$ListOfAnswers[$i]}+1, $ListOfAnswers[$i]);
    }

    ## PRINT OUT RESULTS
    for $j ( $[ .. $#Questions ){
	print "GetQuestion $j is: ". $Questions[$j]->GetQuestion() .
"\n";

	foreach ( @{[ $Questions[$j]->GetAnswers() ]} )
	{
	    print "$_\n";
	}
	
###     Tried this also, but it doesn't work.
###     Should print out:
###     A,B,
###     A,B,C
#	@Answers = $Questions[$j]->GetAnswers();
#	print "Anwsers[0] is: " . $Answers[0] . ", ";
#	print "Answers[1] is: " . $Answers[1] . ", ";
#	print "Answers[2] is: " . $Answers[2] . "\n";
#
#      Would also like to print out results and percentages in a
simple way like this:
#      %Percents = $Questions[$j]->GetPercents();
#      foreach ( @Answers ) {  print "$_ is $Percents{$_}%\n";  }
#      ?????
	
    }
}

$fh->close;

#################################################################

package Question;
use Carp;
BEGIN{ require '/opt/oracle/www/cbsnow/lib/cbs.pl' };

## PRIVATE DATA/METHODS NAMES BEGIN WITH AN UNDERSCORE

### PUBLIC INTERFACE
sub GetTotal    {    (shift)->{_Tot}; }
sub GetColumn   {    (shift)->{_Col}; }
sub GetAnsCount {    (shift)->{_Cnt}; }
sub GetQuestion {    (shift)->{_Q}  ; }
sub GetAnswers  { @{ (shift)->{_A} }; }
sub GetPercent  { %{ (shift)->{_P} }; }
sub GetResults  { %{ (shift)->{_R} }; }

### CONSTRUCTOR
sub new {
    $self = bless {}, shift;
    
    $self->{_Src} = shift; # Data Source
    $self->{_Q}   = shift; # The question
    $self->{_Col} = shift; # Which column has the A for this Q
    $self->{_Cnt} = shift; # The number of possible A for this Q
    
    # Gather answers
    for $i ( $[ .. $self->{_Cnt} ){
	$self->{_A}[$i] = shift;
    }
    
    # Gather results, total num of responses, & percentiles
    $self->{_Tot} = $self->_TallyResults;
    $self->_TallyPercents;
    
    return $self;
}


### PRIVATE METHODS
sub _TallyResults{
    my $self = shift;
    
    unless( defined $self->{_R} )
    {
	my($T,$F);# Total,Filehandle
	    $F = ${ \$self->{_Src} };
        foreach( <$F> )
	{
	    chomp;
	    ## Split each row to get to the answer to this question
	    $answer = ((split (/\|/))[$self->{_Col}]);
	    
	    ## Then tally the answers & Total
	    if( defined $self->_ConfirmResponse($answer) )
	    {
		$self->{_R}{$answer}++;
		$T++;
	    }
	}
    return $T;
    }
}

sub _TallyPercents{
    my $self = shift;
    unless( defined $self->{_P} )
    {
	foreach( @{ $self->{_A} } )
	{
	    $self->{_P}{$_} = 
		&GetPercentile( $self->{_R}{$_}, $self->{_Tot} );
	}
    }
}
  
sub _ConfirmResponse
### CONFIRMS THAT AN ANSWER WE'VE GOTTEN FROM THE
### DATASOURCE IS AN ANSWER TO THIS QUESTION
{
    my $self = shift;
    my($Resp,$Where);

    $Resp = shift;
    undef $Where;

    foreach( @{ $self->{_A} } ){
	$Where = 1, last if ( $Resp eq $_ );
    }
    $Where;
}



------------------------------

Date: Fri, 17 Apr 1998 21:25:23 GMT
From: Eric Bohlman <ebohlman@netcom.com>
Subject: Re: order of declaration - my, local, anonymous sub
Message-Id: <ebohlmanErKu6B.AxH@netcom.com>

Phil R Lawrence <prl2@lehigh.edu> wrote:
: sub report {
:     local $SIG{"INT"} = sub

:         no strict;
:         $dbh->disconnect if ($dbh);

$dbh is treated as a global variable, since there's no lexical variable 
called $dbh currently in scope.

:         exit(0);
:     };
:     my $sid     = "$ENV{ORACLE_SID}";
:     my $dsn     = "dbi:Oracle:$sid";
:     my $user    = "";
:     my $pass    = "";
:     my $dbh;

Only now does $dbh go into scope.  But the signal handler isn't part of 
that scope.


------------------------------

Date: Fri, 17 Apr 1998 17:41:20 -0400
From: Bob Trieger <sowmaster@juicepigs.com>
To: Jayadev Gopinath <jayadev.gopinath@fmr.com>
Subject: Re: perl on windows
Message-Id: <3537CC80.77E@juicepigs.com>

Jayadev Gopinath wrote:
> 
> I am new to PERL on the windows env although I have used Perl with unix.
> 
> I have a cgi script in perl that I want to run when the user POST's a
> form.
> How can I get the web server(enteprise 3.5.1) to recognise that the
> script is a perl script??
> Right now, I am creating a batch file which has a single line
>         perl perl_script.
> I am using this as the cgi program.
> But, how do I pass the STDIN to the perl_script if I use the above
> method??

This is a server question and probably in the server FAQs. It has
nothing to do with perl in reality.

Your best bet would be to check out the documentation for the webserver
and if you can't find an answer there, ask your question in
new:comp.infosystems.www.servers.ms-windows

Good luck
-- 
Bob Trieger               |  Titanic: big boat, bigger
sowmaster@juicepigs.com   |           iceberg, big deal


------------------------------

Date: Fri, 17 Apr 1998 15:54:25 -0600
From: igor@everyware.com
Subject: perl_eval_pv: how to catch errors?
Message-Id: <6h8fi1$19$1@nnrp1.dejanews.com>

Hi,

If I do

	SV* result = perl_eval_pv(string, FALSE);

in my embedded interpretor, and string contains:

	"use Foo;" (literally)

I can get an error from $@, send it back to user, etc.
Ditto for any other syntax or run-time gotchas.
If, however, I try:

	"use Socket qw(foo);" (literally)

the BEGIN block gets executed and the error (about foo not being
imported by Socket.pm) is reported on stderr,
which, among other things looks quite unprofessional for a daemon,
while my $@ contains only "Can't continue after import errors..."

So, how I can catch this kind of errors?

Thanks,
-igor

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/   Now offering spam-free web-based newsreading


------------------------------

Date: 17 Apr 1998 20:04:19 GMT
From: rpinelli@bnr.ca (Rob Pinelli)
Subject: Re: Problems with 'wait' under perl5.004
Message-Id: <6h8ck3$fng@brtph500.bnr.ca>


In article <35379340.FDD9615E@gs.com>, Michael Francis FIR LDN <francm@jeeves.fi.gs.com> writes:

|> I am writing a job control module in perl. This allows me to monitor the
|> status of a number of processes and to check if they are running for
|> more that a desired amount of time (to do this an alarm is fired about
|> every 10 seconds, and the run time for the module is calculated,
|> processes that are running for too long are killed and the logfiles
|> emailed.)
|> 
|> The module worked correctly under perl5.001, we have now upgraded to
|> version 5.004. The symptom is that wait always returns -1 even though
|> the process has spawned a number of child processes. This only occurs
|> following a sigalarm . Does anybody know why this is the case? and if
|> there is any way around this?
|> 

Mike,

  From what I understand, performing a non-blocking wait (which I assume you
are doing) will return -1 if no children have died.  Normally you would write
a "reaper" routine which you would bind to SIG{'CHLD'} so that when a child
signalled its death, the reaper would be called to wait upon it and clean it
up.

  Your SIG{'ALRM'} proc should only worry about calculating the duration of
each child process and killing the overdue ones.  Write a separate procedure
and bind it to SIG{'CHLD'} that will reap dead child processes.  This procedure
will get called when a child dies on its own, or when your alarm procedure
kills one for you.

  If I am mistaken about any of this, feel free to correct me!

--Rob

-- 
Rob Pinelli   rpinelli@nortel.ca     | I do not speak for my
Dept. 3Z31    ISDN Display Services  | employer. However, the   
NORTEL, Inc.  (919) 991-8940         | opinions expressed here may
Research Triangle Park, NC 27709     | be bought for a nominal fee.


------------------------------

Date: Fri, 17 Apr 1998 17:55:32 +0100
From: Toby Heywood <toby@he-net.demon.co.uk>
Subject: Proplem with perl script (I'm new to perl)
Message-Id: <35378983.59A28DF0@he-net.demon.co.uk>

This is a multi-part message in MIME format.
--------------5643F6886BE93374BBED6759
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

I have just started to learn to write perl scripts, I am using the book
Learning Perl.

I have gotten upto what I have called the 5 exercise, and have been
trying to debug my script.

here is the script that I have rewritten from the book.

_____________________________________ START OF CODE

#!/usr/bin/perl
@words = ("camal","llama","oyster");
print "What is your name? ";
$name = <STDIN>;
chop($name);
if ($name eq "Toby") {
        print "Hello, Toby! Back here again? oh well, have fun!\n";
} else {
        print "Hello, $name!\n"; # Ordinary greeting
        print "What is the secret word? ";
        $guess = <STDIN>;
        chop($guess);
        $i = 0; # Try this first
        $correct = "maybe"; # is the guess correct or not?
        while ($correct == "maybe") { # is the guess correct or not?
             if ($words[$i] eq $guess) { # right?
                     $correct = "yes"; # Yes!
             } elsif ($i < 2) { # more words to look at?
                     $i = $i + 1; # look at the next word next time
             } else { # no more words, must be bad
                     print "Wrong, try again.  What is the secret word?
";
                     $guess = <STDIN>;
                     chop($guess);
                     $i = 0; # start check from the beginning
             }
        } # end of while not correct
} # end of "not toby"

________________________________________________ END OF CODE

Anyway, I used the the -w flag for trying to debug the script, and all I
keep getting is this message.  I'm now stuck, and would be grateful if
you can help.

Argument "yes" isn't numeric in eq at perl_exercise_5 line 16, <STDIN>
chunk2.
Argument "maybe" isn't numeric in eq at perl_exercise_5 line 16, <STDIN>
chunk2.

Thanks in advance!
--
Toby Heywood <toby@he-net.demon.co.uk>
Proprietor, Heywood Enterprises
----------------------------------------
Website - http://www.he-net.demon.co.uk/
----------------------------------------


--------------5643F6886BE93374BBED6759
Content-Type: text/x-vcard; charset=us-ascii; name="vcard.vcf"
Content-Transfer-Encoding: 7bit
Content-Description: Card for Toby Heywood
Content-Disposition: attachment; filename="vcard.vcf"

begin:          vcard
fn:             Toby Heywood
n:              Heywood;Toby
org:            Heywood Enterprises
email;internet: toby@he-net.demon.co.uk
title:          Proprietor
x-mozilla-cpt:  ;0
x-mozilla-html: TRUE
version:        2.1
end:            vcard


--------------5643F6886BE93374BBED6759--




------------------------------

Date: Fri, 17 Apr 1998 13:49:41 -0700
From: Glenn Schworak <Glenn.J.Schworak@state.or.us>
Subject: Re: reading values from multi-select list
Message-Id: <3537C065.5E57413E@state.or.us>

Thanks for the reply. I just descovered my problem. It was really stupid!

I had updated the file and somehow got the line attached to the previous
line which ended in a comment. Although my text looked like it was on a
seperate line due to word wrapping, it was really commented out because it
was part of the previous line. And that was the entire problem.

@mylist = $mypage->param('listbox')

Really does work the way it is suposed to.

Sorry to have troubled you.

>>> rootbeer@teleport.com 04/17/98 11:38am >>>
On Fri, 17 Apr 1998, Glenn Schworak wrote:

> I have used the cgi.pl

Maybe you mean CGI.pm?

> to read in parameters passed from a form for some time now. But just ran
> in to a small problem. I can't figure out how to read a list of results
> when there is a multi-select list on my form.

> $mypage->param('listbox')   will hold the entire list of all selected
> items.
> @mylist = $mypage->param('listbox') only copies out the 1st item in the
> list

Really? That second one is in the docs for CGI.pm as having different
behavior. Can you cut your code down to a small example script (say, under
10 lines) which shows this bug?

Hope this helps!

--
Tom Phoenix       Perl Training and Hacking       Esperanto
Randal Schwartz Case:     http://www.rahul.net/jeffrey/ovs/




------------------------------

Date: Fri, 17 Apr 1998 14:56:02 GMT
From: David Corcoran <david.x.corcoran@boeing.com>
To: Curdin Vital <curdin.vital@swisscom.com>
Subject: Re: Send Message to Event Viewer
Message-Id: <35376D82.4F2A@boeing.com>

Curdin Vital wrote:
> 
> Hi,
> 
> How it is possible with Perl to send a message
> to WinNT EventViewer?
> 
> Thank you for the help
>       Curdin

Assuming you really meant the Event Log:

BTW this is included in the ActiveState distribution...

Win32::Eventlog 

     Functions 
     Methods 
     Examples

Functions

Open((out)$EventObj, $SourceName, [$ServerName]) 
(out) $EventObj; 
     Reference to an EventLog Object. 
$SourceName; 
     Name of the source of the event. 
$ServerName; 
     Optional: name of machine. If none, assumes local. 

Open the eventlog on the specified machine, if no server is specified,
the local machine is used. An Eventlog object is returned in $EventObj. 

 

OpenBackup((out)$EventObj, $FileName, [$ServerName]) 
(out)$EventObj 
     Reference to an Eventlog Object. 
$FileName 
     name of the file containing the backup eventlog. 
$ServerName 
     Optional: UNC name of the server containing the backup log. 

Open a backup eventlog and return an object to control it. If
$ServerName is not given the local machine is used.

 

Methods

Backup($filename) 
     $filename 
file to write the eventlog to. 
Save the current open event log to a file 
  
Read($ReadFlags,$RecordOffset,(out)%EventInfo) 
(out) $ReadFlags 
     Specifies how to read log 
$RecordOffset 
     Number of first record 
(out)%EventInfo 
     Event information 
The Read method reads an entry from the eventlog. $ReadFlags can be any
combination of: 

ReadFlag option              Description                
EVENTLOG_FORWARDS_READ       Eventlog is read in        
                             forward chronological      
                             order.                     

EVENTLOG_BACKWARDS_READ      Eventlog is read in        
                             reverse chronological      
                             order.                     

EVENTLOG_SEEK_READ           The read begins at the     
                             record specified by the    
                             $RecordOffset parameter.   
                             Must also specify          

EVENT_LOG_FORWARD_READ or  
EVENTLOG_BACKWARDS_READ.   

EVENTLOG_SEQUENTIAL_READ     The read continues         
                             sequentially from the      
                             last read call.            

See the Report method for information on the %EventInfo hash. 
  
Report($EventInfo) 
$EventInfo 
     A hash containing the event info. 

Reports an event. Implicitly calls RegisterEventSource. 

The options for $Event are:

$Event Options                Description               
EVENTLOG_ERROR_TYPE           Error event               
EVENTLOG_WARNING_TYPE         Warning event             
EVENTLOG_INFORMATION_TYPE     Information event         
EVENTLOG_AUDIT_SUCCESS_TYPE   Success Audit event       
EVENTLOG_AUDIT_FAILURE_TYPE   Failure Audit event.      


$EventInfo contains the following:
Key             Value                                    
Category        integer value for the category of the event (app
defined)                     
EventID         ID value of the Event. Source specific, any
value.                               
Data            The Raw binary data                      
Strings         Any text strings to merge                

GetOldest((out)$oldest)
     Returns the Absolute record number of the oldest record in the
event log. 

GetNumber((out)$NumberOfEvents)
     Returns the number of events.

Clear([ $filename ])
     If the $filename option is given, then the current eventlog is
written to the file Clears the event log.

Example 1

        use Win32::Eventlog;
        sub TEST1
        { 
                my $number, $EventLog;
                Win32::EventLog::Open($EventLog , "System", '') || die
$!;
                $EventLog->GetNumber($number) || die $!;
                print "There are $number records in the System Event
Log\n";
        }

        TEST1

Example 2

        use Win32::Eventlog;
        sub TEST2
        {
                my $number, $EventLog;
                # open the event log.
                Win32::EventLog::Open($EventLog , "PerlApp", '') || die
$!;
                # define the event to log.
                $Event =
                {
                        'EventType' => EVENTLOG_INFORMATION_TYPE,
                        'Category' => 0,
                        'EventID' => 0x1003,
                        'Data' => '',
                        'Strings' => "Test report",
                };
                # report the event and check the error
                $EventLog->Report($Event) || die $!;
        }
        TEST2


------------------------------

Date: 17 Apr 1998 21:12:04 GMT
From: smcdow@arlut.utexas.edu (Stuart McDow)
Subject: Re: Snobby news group
Message-Id: <6h8gj4$5b4$1@ns1.arlut.utexas.edu>

"Andrew F. Lee" <andrewf@cp.pathfinder.com> writes:
>
> I am going to teach you Irish by telling you to read a dictionary.
> It's no use, me walking you through the idiosyncracies of an ancient
> language.  That'd just make you a member of the welfare state.

Irish is a complicated language. If one hasn't been speaking it since
childhood, it will initially look and sound very foreign and
strange. To get a mastery of it requires years of patient study.

Perl is a complicated language. If one's background doesn't involve
lots of programming in C, shell, sed, awk, and regexes, perl will
initially look very foreign and strange. To get a mastey of it
requires years of patient study.

OTOH, to get perl to do something for you without having to be a
master of perl requires a day or two of diligent studying.

The "snobbishness" of this newsgroup stems from the fact that so many
people aren't even taking the time to get the rudiments of the
language.

Why should those who haven't even done their homework expect to get
answers?

--
Stuart McDow                                     Applied Research Laboratories
smcdow@arlut.utexas.edu                      The University of Texas at Austin
  "It is obvious that about 750,000 people ago, Austin was a wonderful City."


------------------------------

Date: Fri, 17 Apr 1998 17:16:02 -0400
From: Bob Trieger <sowmaster@juicepigs.com>
Subject: Re: Snobby news group
Message-Id: <3537C691.45DA@juicepigs.com>

Phil Ptkwt Kristin wrote:
 
> >In article <6h82ft$69c$1@news.scruz.net>, "Database Coder" <dbcoder@juno.com> posted:
 
> >
> >helping people learn to answer there own questions figures heavily
> >into the philosophy of a lot of people here.
> 
> You know what they say, Give a man a fish and he eats for a day.  Teach a
> man how to fish and he has food for a lifetime... Or to paraphrase: give a
> man an opened oyster and he won't get any peals, teach him how to shuck
> his hown oysters and he can find his own pearls. ;-)

Excellent quotes. Sometimes I wonder if these whiners that don't
understand the concept of teaching somebody to fend for themselves have
teenage offspring still in diapers and getting bottle-fed.


-- 
Bob Trieger               |  Titanic: big boat, bigger
sowmaster@juicepigs.com   |           iceberg, big deal


------------------------------

Date: 17 Apr 1998 21:49:16 GMT
From: gbacon@cs.uah.edu (Greg Bacon)
Subject: Re: Snobby news group
Message-Id: <6h8ios$nkk$2@info.uah.edu>

In article <Pine.GSO.3.95.980417155952.14142A-100000@cp.pathfinder.com>,
	"Andrew F. Lee" <andrewf@cp.pathfinder.com> writes:
: Unix gurus tend to be snobbish -- this I understand and expect.

Please justify this claim or give your definition of ``snobbish''.

: It would seem that some of the experienced programmers
: here do not want anyone else to learn Perl.

You're mistaken.  We have more than our fair share of clueless users,
and it is this set from which we do not wish to expand our user base.

If people want comp.lang.perl.newbie-only, they are perfectly free to
suggest it through the proper channels.

Greg


------------------------------

Date: 17 Apr 1998 20:55:09 GMT
From: smcdow@arlut.utexas.edu (Stuart McDow)
Subject: Re: Undef vs. Empty Anon Array ([]) as subroutine parameters
Message-Id: <6h8fjd$350$1@ns1.arlut.utexas.edu>

Allen Choy <achoy@us.oracle.com> writes:
>
> I have a subroutine which expects an array reference as one of its
> parameters.  In the case where the array is empty, is it preferrable
> to a) pass in an undef, or b) to pass in an empty anon array?

You could write the sub so that it accepts both.

sub foo {
  my $a_ref = shift;   # or my ($a_ref) = @_;

  if( ! defined($a_ref) || scalar(@$a_ref) == 0) {
    # it's empty
  }
}

foo();        # empty
foo([]);      # empty
foo([1, 2]);  # not empty 

--
Stuart McDow                                     Applied Research Laboratories
smcdow@arlut.utexas.edu                      The University of Texas at Austin
  "It is obvious that about 750,000 people ago, Austin was a wonderful City."


------------------------------

Date: 8 Mar 97 21:33:47 GMT (Last modified)
From: Perl-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 8 Mar 97)
Message-Id: <null>


Administrivia:

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

To submit articles to comp.lang.perl.misc (and this Digest), send your
article to perl-users@ruby.oce.orst.edu.

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.

The Meta-FAQ, an article containing information about the FAQ, is
available by requesting "send perl-users meta-faq". The real FAQ, as it
appeared last in the newsgroup, can be retrieved with the request "send
perl-users FAQ". Due to their sizes, neither the Meta-FAQ nor the FAQ
are included in the digest.

The "mini-FAQ", which is an updated version of the Meta-FAQ, is
available by requesting "send perl-users mini-faq". It appears twice
weekly in the group, but is not distributed in the digest.

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 V8 Issue 2354
**************************************

home help back first fref pref prev next nref lref last post