[7590] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 1216 Volume: 8

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Oct 22 22:08:03 1997

Date: Wed, 22 Oct 97 19:00:34 -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           Wed, 22 Oct 1997     Volume: 8 Number: 1216

Today's topics:
     Re: Best way to comma seperate a number? mcguirk@indirect.com
     Re: CGI scripts to access client hard drives <sahar@home.net>
     Changing Permissions On Files (Craig A. Shortreed)
     Checking for the existence of subroutines <apeterso@ctberk.com>
     Re: Children becoming ZOMBIE if parent still alive? (dave)
     Children only inherit redirects if use system "perl": s <dan_oct97@unitech.com>
     Re: Data driven code...? <rpsavage@ozemail.com.au>
     Re: Digital UNIX 4.0 and Perl 5.004_01 Problems? <sorokin@vtt.co.jp>
     Re: help: perl and SMTP <rra@stanford.edu>
     Re: Learning Perl... best way? (dave)
     Re: Passing Associative Arrays to a subroutine <bholzman@mail.earthlink.net>
     Re: Passing Associative Arrays to a subroutine (Toutatis)
     Re: Passing Associative Arrays to a subroutine (Jeff Stampes)
     Re: Perl Pad function <rootbeer@teleport.com>
     Re: Random number in perl. (Abigail)
     Re: Regular Expressions and Record Separators <rootbeer@teleport.com>
     Script to save an html browser file into the server. <sahar@home.net>
     Re: setuid not changing uid <rootbeer@teleport.com>
     sorting on primary and secondary key <daftary@cisco.com>
     Re: subscripting a function to get a single return valu <rra@stanford.edu>
     Re: Timing out sys process? <joegottman@worldnet.att.net>
     What might go wrong here and how can I test that? Gerben_Wierda@RnA.nl
     What's wrong with my script ????? (B.S.LEE)
     Why wont it work on the Web ? <nishin@bekkoame.or.jp>
     XS question:  string parameter (allocation) (James L. McGill)
     XS question: memory mapping <klee@geocities.com>
     Digest Administrivia (Last modified: 8 Mar 97) (Perl-Users-Digest Admin)

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

Date: Wed, 22 Oct 1997 19:51:24 -0600
From: mcguirk@indirect.com
To: mcguirk@indirect.com
Subject: Re: Best way to comma seperate a number?
Message-Id: <877567593.19219@dejanews.com>

pojo@gte.net.nospam (Eric) writes:
>Okay, I found this in the FAQ.  Why does it work?  More specifically, why
>does:
>
> 1 while s/^(-?\d+)(\d{3})/$1,$2/;
>
>do what it does??  What is that 1 doing in there?
>
>-- Eric

A modifier like 'while', 'if', or 'unless' can be tacked on to the
end of any simple statement.  In this case the '1' is just a meaningless
statement that lets the while test condition (which does all the work)
execute until it returns a non-true value.

You could write

	while(s/^(-?\d+)(\d{3})/$1,$2/) {}

which would do the same thing (and is arguably less confusing).

The test condition keeps inserting a comma before the last three digits
of a block of four or more digits until it can't anymore.

-------------------==== Posted via Deja News ====-----------------------
      http://www.dejanews.com/     Search, Read, Post to Usenet


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

Date: Wed, 22 Oct 1997 14:46:44 -0700
From: Sahar Madani <sahar@home.net>
To: petri.backstrom@icl.fi
Subject: Re: CGI scripts to access client hard drives
Message-Id: <344E7444.8DF53D2D@home.net>

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

You can get the free script from this site !

http://www.terminalp.com/scripts/

Petri Backstrom wrote:
> 
> praveen_s@trigent.com wrote:
> >
> > I am looking for help on Perl CGI scripts or mechanisms to pop up a
> > file
> > dialog box, read the selected file which resides on the clients hard
> > drive and pass the data to the server for processing. Can this be done
> > using Perl and HTML only? (Without any client side scripting).
> 
> You can use the file upload feature Netscape invented
> (and which also Microsoft supports nowadays), and
> upload a user selected file for processing on the
> server.
> 
> > This also holds good for saving, say a text file on the clients hard
> > drive.
> 
> You can send the file back, and let the user choose
> whether to run or save it or not.
> 
> You cannot access files directly on the client system,
> unless you resort to signed Java applets (and browsers
> that support it; done differently for Netscape Navigator
> and Microsoft Internet Explorer), or an ActiveX control
> (also signed), a plugin (must be user installed) or
> your own server program to be installed and run on
> the client.
> 
> For the parts above that you can do, use the CGI.pm
> Perl module.
> 
> regards,
>  ...petri.backstrom@icl.fi
>     ICL Data Oy
>     Finlan
--------------B5BFB0B3DCEA6DA73590FC03
Content-Type: text/x-vcard; charset=us-ascii; name="vcard.vcf"
Content-Transfer-Encoding: 7bit
Content-Description: Card for Sahar Madani
Content-Disposition: attachment; filename="vcard.vcf"

begin:          vcard
fn:             Sahar Madani
n:              Madani;Sahar
org:            @Home Network
adr:            ;;;Redwood City;California;;U.S.A
email;internet: sahar@home.net
tel;work:       415-569-5160
tel;fax:        415-569-5100
x-mozilla-cpt:  ;0
x-mozilla-html: TRUE
version:        2.1
end:            vcard


--------------B5BFB0B3DCEA6DA73590FC03--



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

Date: 22 Oct 1997 22:55:30 GMT
From: cshortreed@valnet.com (Craig A. Shortreed)
Subject: Changing Permissions On Files
Message-Id: <62m092$5kf$1@news1.rmi.net>

I am writing a perl script that will allow a user to upload a file from a web 
page and place it in their home directory, the problem is that user www wants 
to own that file.  I've tried to chown it and it won't change ownership, I 
tried to 'cp -R' another file that was owned by the user so that when the new 
file overwrote it the permissions would stay with it, but that didn't work 
either.  Is there any way to open a file, write to it and change the ownership 
to the person who owns the directory?

Thank You,
Craig Shortreed
cshortreed@valnet.com



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

Date: Wed, 22 Oct 1997 18:04:11 -0700
From: Arvid Peterson <apeterso@ctberk.com>
Subject: Checking for the existence of subroutines
Message-Id: <344EA28A.CF0C83D6@ctberk.com>

Is there any way in perl 4 to check for the existence of a certain
subroutine in a program and call that subroutine only if it exists??
The reason for this is, I need to call subroutines for specific variable
values, and want to name the subroutine with the value. Let's say...

$var1= "grub";
<more perl code>
&$var1;

I have tried...
&$var1 || warn "subroutine $var1 is not defined\n";

as well as...
#define FIRST &$var1
#if FIRST
   &$var1
#endif

Any other suggestions???
Thanks in advance.




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

Date: Thu, 23 Oct 1997 00:32:46 GMT
From: over@the.net (dave)
Subject: Re: Children becoming ZOMBIE if parent still alive?
Message-Id: <344e9ab1.1188412@news.one.net>

toutatis@_SPAMTRAP_toutatis.net (Toutatis) wrote:

>In article <344cf15a.0@news.liberty.com>, dsalch@liberty.com wrote:
>
>> Keyword: 
>> 
>> I am working on a program that launches children that run an indetermined
>amount of time
>> and then exit normally, but the parent runs forever, launching
>> children as needed to do certain tasks. The problem is that when the children
>> die they go into zombies until the parent dies, which normally would
>> be never. I have tried killing the processes form the parent, 
>> forking children of children, etc. and nothing works without leaving
>> some zombie running somewhere.
>
>According to Sriram Srinivasan in "Advanced Perl Programming",
>$SIG{CHLD} = sub {wait ()};
>in your code should do what you want.
>
>-- 
>Toutatis

The sub{wait()} became a problem to me when I wanted to explicity wait on a
forked child to complete (to get exit status).  One too many waits were done
and the parent hung.  Rather than keep redefining the CHLD handler, I looked
for another alternative.

I had some code that was called periodically, so I did the following (see
waitpid()):

use POSIX ":sys_wait_h";

# Insert in code that is called periodically:
for(;;) { last if waitpid( -1, &WNOHANG ) <= 0; }


Seems to work for me, though zombies are only cleaned up periodically.

Dave
|
| Please visit me at http://w3.one.net/~dlripber
|
| For reply by email, use:
| dlripber@one.net
|________


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

Date: 23 Oct 1997 00:01:26 GMT
From: Dan Harkless <dan_oct97@unitech.com>
Subject: Children only inherit redirects if use system "perl": should be NT FAQ!
Message-Id: <62m44m$nbp$1@speedx1.speed.net>

I am using Gurusamy Sarathy's binary distribution of 5.004_02 on NT.  I was
trying to get a pair of scripts to work where a parent script writes some
output to a LOG file then redirects STDOUT and STDERR to the LOG and calls
another perl script with system().

This absolutely fails to work if you call the second script using its name:

    system("callee.pl arguments");

The output of the callee just disappears!  It doesn't go to the log file,
the terminal, or anywhere.

I tried various workarounds including doing a ">" in the system string and
tying STDERR to STDOUT in the callee -- everything I tried failed -- except
for one thing:

    system("perl -S callee.pl arguments");

Calling the perl interpreter directly appears to be the only way to get the
callee to respect output redirections.  The -S causes perl to search the
path for callee.pl rather than just looking for it in the current directory.

This should certainly be in the Perl for Win32 FAQ -- I'm sure it burns a
lot of people.

--
Dan Harkless          Unitech Research, Inc.         <dan_oct97@unitech.com>

NOTE:  This is a monthly mail alias used to post to the Usenet without
conSPAMinating my real address.  If you are replying after October 1997,
your mail may bounce.  If so, replace 'oct' with the current month's abbrev.


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

Date: Thu, 23 Oct 1997 09:12:01 +1100
From: Ron Savage <rpsavage@ozemail.com.au>
Subject: Re: Data driven code...?
Message-Id: <344E7A31.1EE2@ozemail.com.au>

Pierre Fortin wrote:
> 
> Hi,
> 
> I'm trying to write code to read lines from a file and invoke specific
> subroutines based on the input data (i.e., $data = "foo", so invoke:[snip]

Alternately, use a Perl Finite State Machine module. Basically you specify a regular expression and a sub 
name, and when your input matches the RE, the sub is called. I have written such a module, but not posted it. 
It comes with examples, and a module which even writes your script! Email me for a copy if interested. 
-- 
Cheers,
Ron Savage
Office: savage.ron.rs@bhp.com.au
Home (preferred): rpsavage@ozemail.com.au


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

Date: Thu, 23 Oct 1997 10:30:27 +0900
From: Alexandre Sorokine <sorokin@vtt.co.jp>
Subject: Re: Digital UNIX 4.0 and Perl 5.004_01 Problems?
Message-Id: <344EA8B3.3EF81AE@vtt.co.jp>

win95 wrote:

> Is anyone aware of any problems running 5.004_01 on Digital UNIX 4.0.
> Please feel free to email.

I had some problems compiling Perl 5.004_01on Digital Unix 4.0A with gcc
2.7.2.2, but after upgrading to gcc 2.7.2.3  they vanished.

> Vazquez2@ixc.net
>
> thanks.

Hope this helps,
--
Sorokine



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

Date: 22 Oct 1997 15:56:45 -0700
From: Russ Allbery <rra@stanford.edu>
Subject: Re: help: perl and SMTP
Message-Id: <m3hga9be4y.fsf@windlord.Stanford.EDU>

dan vinnola <dvinnola@wolonline.net> writes:

> I am trying to create a script that will read a file and build an email
> to send to an SMTP host.  Has anyone done that?

What's hard about this?

open (SENDMAIL, '| /usr/lib/sendmail -t -oi -oem')
    or die "can't fork sendmail: $!\n";
open (FILE, 'some.file') or die "can't open file: $!\n";
print SENDMAIL $_ while (<FILE>);
close SENDMAIL;
die "sendmail exited with status $?\n" unless ($? == 0);
close FILE;

If you're using a non-Unix OS, you'll probably want to get a sendmail
replacement, or you can look at libnet which has a Net::SMTP module.

-- 
#!/usr/bin/perl -- Russ Allbery, Just Another Perl Hacker
$^=q;@!>~|{>krw>yn{u<$$<[~||<Juukn{=,<S~|}<Jwx}qn{<Yn{u<Qjltn{ > 0gFzD gD,
 00Fz, 0,,( 0hF 0g)F/=, 0> "L$/GEIFewe{,$/ 0C$~> "@=,m,|,(e 0.), 01,pnn,y{
rw} >;,$0=q,$,,($_=$^)=~y,$/ C-~><@=\n\r,-~$:-u/ #y,d,s,(\$.),$1,gee,print


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

Date: Thu, 23 Oct 1997 00:44:53 GMT
From: over@the.net (dave)
Subject: Re: Learning Perl... best way?
Message-Id: <344e9c21.1555970@news.one.net>

"Lee Davies" <lee.davies@NOSPAMmicrotest.co.uk> wrote:

>My company launched our new web site just before Christmas of last year and
>we have been happily plodding along with HTML and Javascript.
>
>We now want to do more with our site as we have commercial space and have
>our own cgi-bin.
>
>So... any recommendations on the best way to learn Perl?  My background is
>in Unix programming using C, C++ and shell scripting so I'm fairly ok with
>the Perl scripts I have looked at so far, I just need some guidance...
>
>All replies much appreciated, although e-mail's would be best.
>
>Thanks.
>
>lee.davies@microtest.co.uk

I liked Programming Perl (Camel Book) because I could take my time covering the
more complicated issues from a comfortable chair with my trusty highlighter.
Then go back and re-read them 3 or 4 times.  My background is about the same as
yours.

Dave
|
| Please visit me at http://w3.one.net/~dlripber
|
| For reply by email, use:
| dlripber@one.net
|________


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

Date: Wed, 22 Oct 1997 20:08:50 -0400
From: Benjamin Holzman <bholzman@mail.earthlink.net>
To: pasn@ix.netcom.com
Subject: Re: Passing Associative Arrays to a subroutine
Message-Id: <344E9592.4E1E1AF1@mail.earthlink.net>

[posted & mailed]

pasn@ix.netcom.com wrote:
> 
>    I am trying to pass 2 associative arrays as arguments to a
> subroutine.  I get the values of the first array only   and the code
> looks  like
> 
> ********
> 
>      ...
>      ....
>      &comp_str(%enustr,%frastr);
>      ...
>      ...
>      ..
> 
> #======Begin Subroutine  ====================
> sub comp_str{
>     local(%enustr,%langStr);
>     (%enustr,%langStr)=@_;
> 
>     foreach $key (keys(%enustr))
>     {
>          if ($enustr{$key} ne $langStr{$key}){
>             print  "\n";
>             print $key ;
>             print  "\t";
>             print  $enustr{$key};
>             print "\t";
>             print  $langStr{$key};
>             print "\n";
>             }
>    }
> }
> 
> ********
> 
> what do I need to do differently?
> 
> Thanks
> 
> raj

Read up on subroutines in perl. Then, either use prototypes or pass
references to the hashes instead of the hashes themselves.

Prototypes:

 ...
&comp_str(%enustr,%frastr);
 ...

sub comp_str (\%\%) {
  my %enustr = %{shift};
  my %langStr = %{shift};
 ...

References:

 ...
&comp_str(\%enustr,\%frastr);
 ...

sub comp_str {
  my %enustr = %{shift};
  my %langStr = %{shift};
 ...


Hmm, there's a nice symmetry to those two examples.  Wonder if it's a
coincidence... ;-)

HTH,

Benjamin Holzman


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

Date: 23 Oct 1997 00:35:12 GMT
From: toutatis@_SPAMTRAP_toutatis.net (Toutatis)
Subject: Re: Passing Associative Arrays to a subroutine
Message-Id: <toutatis-ya023180002310970235120001@news.euro.net>

pasn@ix.netcom.com wrote:

>    I am trying to pass 2 associative arrays as arguments to a
> subroutine.  I get the values of the first array only   and the code
> looks  like

>      &comp_str(%enustr,%frastr);
[...]
> sub comp_str{
>     local(%enustr,%langStr);
>     (%enustr,%langStr)=@_;
[...]
> what do I need to do differently?

Read any first chapter of any Perl tutorial for the explanation, but what
it comes down to is that if you want to pass more than one (associative)
array through @_, you've gotta pass them by reference, since the arrays are
flattened to one big list.

&comp_str(\%foo,\%bar);
#or as anonymous hashes
&comp_str({%foo},{%bar});

sub comp_str {
   my %foo = %{$_[0]};
   my %bar = %{$_[1]};
   #accessable by 
   $foo{element};
   #or just by reference:
   my ($foo,$bar) = @_;
   #accessable by
   $foo->{element};
}

You're using local. That probably does not you want. If you want to declare
a private variable, use 'my' instead. Forget about local until you've read
another few chapters...

-- 
Toutatis


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

Date: 23 Oct 1997 00:20:05 GMT
From: stampes@xilinx.com (Jeff Stampes)
Subject: Re: Passing Associative Arrays to a subroutine
Message-Id: <62m57l$eg8$1@neocad.com>

pasn@ix.netcom.com wrote:

:    I am trying to pass 2 associative arrays as arguments to a
: subroutine.  I get the values of the first array only 

Pass by reference instead.  see the perlref manpage for further
details...
 
: looks  like

: ********

:      ...
:      ....
:      &comp_str(%enustr,%frastr);

   Would become:
       &comp_str(\%enustr,\%frastr);

: what do I need to do differently?

You'll have to derenferece in the subroutine.  But rather than 
showing you that, I'll leave it as an exercise after reading the
appropriate documentation.

--
Jeff Stampes -- Xilinx, Inc. -- Boulder, CO -- jeff.stampes@xilinx.com


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

Date: Wed, 22 Oct 1997 18:53:00 -0700
From: Tom Phoenix <rootbeer@teleport.com>
To: George Pieri <gmpieri@carroll.com>
Subject: Re: Perl Pad function
Message-Id: <Pine.GSO.3.96.971022185222.7008H-100000@usertest.teleport.com>

On Wed, 22 Oct 1997, George Pieri wrote:

> I wanted to left pad or right pad a string , so that the string would
> be x characters wide. 

> It looks like I can use the pack function to do padding as described
> above but I wanted to make sure that no other better function exists.

In what way would another function be better? :-)

-- 
Tom Phoenix           http://www.teleport.com/~rootbeer/
rootbeer@teleport.com  PGP   Skribu al mi per Esperanto!
Randal Schwartz Case:  http://www.rahul.net/jeffrey/ovs/
              Ask me about Perl trainings!



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

Date: 22 Oct 1997 22:07:49 GMT
From: abigail@fnx.com (Abigail)
Subject: Re: Random number in perl.
Message-Id: <slrn64sudh.qp.abigail@betelgeuse.wayne.fnx.com>

Eric Persson (persson@tkj.se) wrote on 1513 September 1993 in
<URL: news:344E49E4.3EC@tkj.se>:

comp.lang.perl has been dead for eons. Don't post there.

++ I need to make a random nr in perl. Someone got a simple syntax for
++ this??

What part of the manual didn't you understand?

++ Please help me and reply via e-mail!

No. If you can't be bothered to read the group after asking a
question, it wasn't important.



Abigail
-- 
perl -wle 'print "Prime" if (1 x shift) =~ /^(?!(11+)\1+$)/'


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

Date: Wed, 22 Oct 1997 18:51:18 -0700
From: Tom Phoenix <rootbeer@teleport.com>
To: Corey Bufi <bufic@cs.rpi.edu>
Subject: Re: Regular Expressions and Record Separators
Message-Id: <Pine.GSO.3.96.971022184852.7008G-100000@usertest.teleport.com>

On Mon, 20 Oct 1997, Corey Bufi wrote:

> I want to set the input record separator to a regurlar expression
> so that a file can be segmented according to any one of a set of
> multi-character delimiters.  For example, I want to set the
> delimiting condition to be case insensitive.  From what I gather,
> this can't be done.  Is this correct?

Sure, you can do this; you just have to wait for the future version of
Perl which supports it. :-)

In the mean time, if there's a module which does what you want, it should
be listed in the module list on CPAN. If you don't find one to your
liking, you're welcome and encouraged to submit one! :-)  Hope this helps! 

    http://www.perl.org/CPAN/
    http://www.perl.com/CPAN/

-- 
Tom Phoenix           http://www.teleport.com/~rootbeer/
rootbeer@teleport.com  PGP   Skribu al mi per Esperanto!
Randal Schwartz Case:  http://www.rahul.net/jeffrey/ovs/
              Ask me about Perl trainings!



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

Date: Wed, 22 Oct 1997 14:49:49 -0700
From: Sahar Madani <sahar@home.net>
Subject: Script to save an html browser file into the server.
Message-Id: <344E74FD.3A07AB3E@home.net>

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

how is it possible to save (publish) a CGI cookie based HTML file onto
the server from browser ?
--------------973F116036CBA3EACCF1029F
Content-Type: text/x-vcard; charset=us-ascii; name="vcard.vcf"
Content-Transfer-Encoding: 7bit
Content-Description: Card for Sahar Madani
Content-Disposition: attachment; filename="vcard.vcf"

begin:          vcard
fn:             Sahar Madani
n:              Madani;Sahar
org:            @Home Network
adr:            ;;;Redwood City;California;;U.S.A
email;internet: sahar@home.net
tel;work:       415-569-5160
tel;fax:        415-569-5100
x-mozilla-cpt:  ;0
x-mozilla-html: TRUE
version:        2.1
end:            vcard


--------------973F116036CBA3EACCF1029F--



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

Date: Wed, 22 Oct 1997 18:48:02 -0700
From: Tom Phoenix <rootbeer@teleport.com>
To: Scott Smith <scottsmi@blue.seas.upenn.edu>
Subject: Re: setuid not changing uid
Message-Id: <Pine.GSO.3.96.971022184519.7008F-100000@usertest.teleport.com>

On 20 Oct 1997, Scott Smith wrote:

> I wrote earlier <SCOTTSMI.97Oct19161658@blue.seas.upenn.edu>
> > When I try running a setuid perl script, it runs as the user invoking
> > the script.
> 
> I should have added that I am using perl5.003, whichever version was
> included with Redhat Linux/Intel 4.0.  The question is, is there
> something I should check for a wrong setup (both the script and suidperl
> seem to have the right permissions) or is this a bug in what I had
> installed.

Probably suidperl or perl are mis-compiled and aren't recognizing the
set-id bits. But there are other possibilities. I recommend compiling Perl
from the source (from CPAN), being sure to turn on the ability to have
set-id scripts. Make sure it passes all of the tests (from 'make test')
before you install it. Then, if you're still having troubles, let me know
or post here. Good luck! 

-- 
Tom Phoenix           http://www.teleport.com/~rootbeer/
rootbeer@teleport.com  PGP   Skribu al mi per Esperanto!
Randal Schwartz Case:  http://www.rahul.net/jeffrey/ovs/
              Ask me about Perl trainings!



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

Date: Wed, 22 Oct 1997 18:34:45 -0700
From: Kuntal M Daftary <daftary@cisco.com>
Subject: sorting on primary and secondary key
Message-Id: <Pine.GSO.3.96.971022183042.17766A-100000@daftary-ultra.cisco.com>

hi fellas!

i had a queer problem.

i have a hash of hashes like this:

%HOH = {
	 name1 => {
		     "time" => "9999999999",
		     "other" => "whatever",
                  },
	 name1 => {
		     "time" => "8888888888",
		     "other" => "whatever",
                  },
	 name2 => {
		     "time" => "9999999999",
		     "other" => "whatever",
                  },
	 name2 => {
		     "time" => "8888888888",
		     "other" => "whatever",
                  },
        }

and i need to sort this first on basis of "nameX" and the within that based on
"time". how can i achieve that?

Kuntal M. Daftary   Cisco Systems Inc 
Ph: 408 527 9789    170 W. Tasman Dr 
daftary@cisco.com   San Jose CA 95134



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

Date: 22 Oct 1997 15:53:46 -0700
From: Russ Allbery <rra@stanford.edu>
Subject: Re: subscripting a function to get a single return value
Message-Id: <m3k9f5be9x.fsf@windlord.Stanford.EDU>

Tim Gray <tim@hcirisc.cs.binghamton.edu> writes:

> I just tried something like this

> 	$foo = ($dbh->sql("select foo from bar"))[0][0]

> and it didn't work.

What about it didn't work?  I've done similar things to that before and
had them work the way I expected....

-- 
#!/usr/bin/perl -- Russ Allbery, Just Another Perl Hacker
$^=q;@!>~|{>krw>yn{u<$$<[~||<Juukn{=,<S~|}<Jwx}qn{<Yn{u<Qjltn{ > 0gFzD gD,
 00Fz, 0,,( 0hF 0g)F/=, 0> "L$/GEIFewe{,$/ 0C$~> "@=,m,|,(e 0.), 01,pnn,y{
rw} >;,$0=q,$,,($_=$^)=~y,$/ C-~><@=\n\r,-~$:-u/ #y,d,s,(\$.),$1,gee,print


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

Date: Wed, 22 Oct 1997 19:52:03 -0400
From: Joe Gottman <joegottman@worldnet.att.net>
Subject: Re: Timing out sys process?
Message-Id: <344E91A3.5F34@worldnet.att.net>

David Mills wrote:
> 
> Hey, all...
> 
> I am writing a script to use the UNIX "rsh" command to query all the
> IP-based hosts in our building. Since the list I receive from "ypcat
> hosts" includes Macs, PC's, printers, router boxes, etc. that have IP
> addresses but aren't UNIX boxes, I don't want my script to hang trying
> to send a UNIX command to, say, a printer.
> 
> Question: how can I get my program to time out a UNIX command generated
> via PERL's `` or system() call? So far, I've tried creating a string
> variable like this:
> 
>     $time_bomb = "sleep 5; kill -9 `ps -ef | egrep \"rsh $ip_addr\" |
> egrep -v egrep | awk '{print $2}'`";
> 
> and then planting it in the middle of my command like this:
> 
>     `$time_bomb&; rsh $ip_addr $remote_command`;
> 
> in the hopes of giving the "rsh" command about five seconds to get its
> act together and exit before my "$time_bomb" command wakes up, isolates
> the pertinent process ID and kills it.
> 
> I have not mastered the shell-syntax intricacies to carry out my
> shell-ish plot, nor am I convinced that this is the best, most
> straight-forward way of doing what I want.
> 
> 'Suggestions?
> 
>

   There's an example of doing exactly this in the book Advanced Perl
Programming.
Try this:

   {
   local $SIG{ALRM} = sub {die "Timed out";}
   eval
      {
      alarm 10; #Your call has 10 seconds to work.
      $time_bomb = `ps -ef | egrep \"rsh $ip_addr\" |egrep -v egrep |
awk '{print $2}'`;
            #Do your Unix call.
     alarm 0; #If it works, turn off the alarm.
     }
  print "Failed\n" if $_ =~ /Timed Out/; #Check to see if eval died.
-- 
Joe Gottman
joegottman@nospam.worldnet.att.net

[Remove nospam to reply]


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

Date: Wed, 22 Oct 1997 20:54:17 GMT
From: Gerben_Wierda@RnA.nl
Subject: What might go wrong here and how can I test that?
Message-Id: <EIH0qH.J75@RnA.NL>

I was trying to speed up a program by using the // empty pattern trick

========================================================
warn "Trying to match header on: $matchline\n" if $opt_verbose;
/$matchline/;   # Force pattern compile
foreach my $headerline (@header) {
    if ($headerline =~ //) { # Speed: use last compiled pattern
    warn "Match on: $headerline\n" if $opt_verbose;
========================================================

And the output shows (on the first entry in this foreach loop):

========================================================
Trying to match header on: ^Subject: pipe
Match on: From rpols@trouw.nl  Mon Oct 13 18:05:39 1997
========================================================

In fact, it matches on any pattern, as if it is a real empty pattern which 
always matches. This stopped working (it used to work, as it should) after a 
rewrite, so I cannot easily find out what triggers this.

Am I correct in thinking that this is probably a perl bug (using perl-5.004)? 
And do people have ideas how I can find out what is going on? Can I look 
somewhere what perl thinks the 'latest pattern' is?

Thanks,

-- 
Gerben_Wierda@RnA.nl (Gerben Wierda)
"If you don't know where you're going, any road will take you there"
Paraphrased in Alice in Wonderland, originally from the Talmud.

Renee: "Met veel koper maakt men hoempa." (After hearing Brahms' 
Festouverture)


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

Date: Thu, 23 Oct 1997 16:23:42 GMT
From: bslee@pl.jaring.my (B.S.LEE)
Subject: What's wrong with my script ?????
Message-Id: <62m9kc$i0f@news2.jaring.my>

I am wrote a Perl Script to redirect browser to another URL but it
don't work on my PC.
I am using Microsoft Personal Web server as my web server in my PC and
I am using Dial Up connection connect to Internet through my ISP. 
I am testing my script directly on my PC. 
I connect to Internet, then I locate my PC's browser (Internet
Explorer 3.0) to my PC URL(host and domain name), then I try to access
the CGI script using my browser through html form using post and also
get method.
The browser returned the error message that 
"The request header was not found"
I have try using another script to view the data passing to the script
but the data can be sent to cgi script and that script does display
the data passing to the script.
When I use my redirect script, it can't work.
The below is my redirect script.


if ($ENV{'REQUEST_METHOD'} eq 'GET')
{
        $buffer = $ENV{'QUERY_STRING'};
        #read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	@pairs = split(/&/, $buffer);
	foreach $pair (@pairs)
	{
		($name, $value) = split(/=/, $pair);
		$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		$contents{$name} = $value;
	     
	}
}

&logit if $contents{'location'};

sub logit {

if ($contents{'location'} eq "Infoseek")
   {
   $location = "http://www.infoseek.com";
   }
if ($contents{'location'} eq "AltaVista")
   {
   $location = "http://altavista.digital.com";
   }
if ($contents{'location'} eq "WebCrawler")
   {
   $location = "http://www.webcrawler.com";
   }


print "HTTP/1.0 303 See Other";
print "Location: $location\n\n";

exit;
}





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

Date: Thu, 23 Oct 1997 08:52:49 +0900
From: Mic <nishin@bekkoame.or.jp>
Subject: Why wont it work on the Web ?
Message-Id: <344E91D1.61EE@bekkoame.or.jp>

I hope there is someone out there who can help again.

I have this program :-
*******************************************************


#!/usr/local/bin/perl -w

print "Content-type: text/html\n\n";

$user_file = "/xxz/public_html/passw/.htpasswd";
$wizard = "webmaster";

if ($ENV{'REQUEST_METHOD'} ne "POST") {
	print "This script should be referenced with a METHOD of POST.\n";
	print "If you don't understand this, see this ";
	print "<A
HREF=\"http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overview.html\">forms
overview</A>.\n";
	exit(1);
}

#if ($ENV{'CONTENT_TYPE'} ne "application/x-www-form-urlencoded") {
#	print "This script can only be used to decode form results. \n";
#	exit(1);
#}

$input = <STDIN>;
chop($input);
print $input."\n";

if ($input =~ /^user=(.*)&newpasswd1=(\S*)&newpasswd2=(\S*)\s*$/) {
	$user = $1;
	$p1 = $2;
	$p2 = $3;

} else {
	print "This script was accessed from the wrong form.\n";
	print "$input\n";
	exit(1);
}
$user = "dog";
$p1 = "dog";
$p2 = "dog";

# best doens't support remote_user, so we're screwed.  Must assume
# that the user who is making changes is the wizard.
#$u = $ENV{'REMOTE_USER'};
$u = $wizard;

if (($u ne $wizard) && ($u ne $user)) {
	print "<TITLE>User Mismatch</TITLE>";
	print "<H1>User Mismatch</H1>";
	print "The username you gave does not correspond with the ";
	print "user you authenticated as.\n";
	exit(1);
}

if ($p1 ne $p2) {
	print "<TITLE>Password Mismatch</TITLE>";
	print "<H1>Password Mismatch</H1>";
	print "The two copies of your the password do not match. Please";
	print " try again.\n";
	exit(1);
}

$tn = "$$.passwd.txt";

print $tn;
print $user_file;

open(TEMP, ">$tn")
	|| die "Can't open temp file passwd.$$: $!\n";

open(USER_FILE, "<$user_file") 
	|| die "Can't open password file $user_file: $!\n";

$found = 0;
while(<USER_FILE>) {
    if (/^$user:/) {
	&change_password($user, $p1);
	$found = 1;
		
    } else {
	print TEMP;
    }
}	

# add the user if they're not found.
if (!$found) {
    &change_password($user, $p1);
}

close(TEMP);
close(USER_FILE);
print "FINISHED";
unlink($user_file);
rename($tn, $user_file);

chmod 0760, $user_file;

print "<TITLE>Successful Change</TITLE>";
print "<H1>Successful Change</H1>";
print "Your password has been successfully changed.<P>";
exit(0);



sub to64 {
	# From local_passwd.c (C) Regents of Univ. of California blah blah 
	# 0 ... 63 => ascii - 64

	$itoa64 =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

	local($v, $n) = @_;
	local($s);
	
	while (--$n >= 0) {
		$s .= substr($itoa64, ($v % 64), 1);
		$v >>= 6;
	}
	
	return $s;
}


sub change_password {
	local($user, $pw) = @_;

	srand;
	$salt = &to64(int(rand(2147483648)), 2);
	$cpw = crypt($pw, $salt);

	print TEMP "$user:$cpw\n";
}


******************************************************
Which is to change or add new passwords to a file called .htpasswd. The
program works OK after commenting out the section below.

#if ($ENV{'REQUEST_METHOD'} ne "POST") {
#	print "This script should be referenced with a METHOD of POST.\n";
#	print "If you don't understand this, see this ";
#	print "<A
HREF=\"http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overview.html\">forms
overview</A>.\n";
	exit(1);
#}

Then I ran it on the Telnet, inputing the $input string & it works OK.

My problem comes when I run the program from my web page. The program
sends back messages upto & including the:- 

print $user_file;

but after that there is nothing. The web page says document done in the
status bar. but the program doesn't seem to have reached the end of the
program. I was expecting:-

print "<TITLE>Successful Change</TITLE>";
print "<H1>Successful Change</H1>";
print "Your password has been successfully changed.<P>";

section to be printed. I wonder if has something to do with the Open()
commands.

I hope you can help.

Mic


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

Date: 22 Oct 1997 18:20:48 -0500
From: fishbowl@fotd.netcomi.com (James L. McGill)
Subject: XS question:  string parameter (allocation)
Message-Id: <62m1og$cpl$1@fotd.netcomi.com>

Hello all!

I am starting with XS and I have a C lib with a function that
manipulates a string.

For instance, the C function is:

	int foo(char* s);


The XS code is:


	foo(s)
		char* s
		CODE:
			RETVAL = foo(s);
		OUTPUT:
		s
		RETVAL


the perl to call that would be something like:

	$s = 1024x" " #Because I cannot malloc() ?
	$i = foo($s); # $s will be /replaced/ in foo()

(I'm having no problem linking it to my library, so the function works ok)

Now the problem:  I do not want to pre-initialize $s that way,
if I can avoid it.  I am not even sure that that really does
what I think it does.

I thought about putting a 
	CODE:
		s = malloc(1024);
		...
		
into the XS, but I do not have the opportunity to free it, so that
seems like a bad idea (memory leak?).  I do not want to rewrite the C
library (pretending that I cannot -- discipline you know).  I realize
that GC will take care of the allocated memory, but I may call this
function an arbitrary number of times.
		
I suppose I could wrap the whole thing in a C++ object 
with a construct/destroy action... but that's not really what
I was trying to do.

What do you do with these things?

--
g-r-a-t-e-f-u-l-l-y---[   email:<fishbowl@conservatory.com>   ]---l-i-v-i-n-g
d-e-a-d-i-c-a-t-e-d---[     http://www.conservatory.com/      ]-----l-i-g-h-t
Loan-department manager:  "There isn't any fine print.  At these
interest rates, we don't need it."


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

Date: Wed, 22 Oct 1997 14:14:27 -0700
From: Andrew Lee <klee@geocities.com>
Subject: XS question: memory mapping
Message-Id: <344E6CB3.3D36@geocities.com>

Hi,

I'm making an xs for the mmap function in sys/mman.h. mmap returns a
caddr_t and in my C program I cast the return from mmap to a u_short*
and I use it as an array of unsigned short. I need to convert it to an
AV type so I can do this in perl:

@array = Mman::mmap(....);

What I have now gives me a warning: illegal pointer combination. I can't
use av_make here because that's just a copy. Has this been done or does
any body have any clue? 

AV*
mmap(len, prot, flags, fildes, off = 0)
    size_t len
    int prot
    int flags
    int fildes
    long off
    PREINIT:
    caddr_t addr; 
    CODE:
    addr = mmap(0, len, prot, flags, fildes, off);
    RETVAL = (I16*) addr;
    OUTPUT:
    RETVAL

Thanks.

Andrew


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

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 1216
**************************************

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