[13738] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 1148 Volume: 9

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Oct 22 05:07:16 1999

Date: Fri, 22 Oct 1999 02:05:09 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <940583109-v9-i1148@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Fri, 22 Oct 1999     Volume: 9 Number: 1148

Today's topics:
        Annoying file open problem <aneely@softouch.on.ca>
    Re: Annoying file open problem (Alan Curry)
    Re: Annoying file open problem <aneely@softouch.on.ca>
        Attn:  Perl/CGI wizards.  Your expertise is needed.  Si <bob>
        Can I use flock as lever to create reliable unique cook (Ben Blish)
        Code example help? <trent@jps.net>
    Re: Converting String To Upper and Lower Case (Craig Berry)
    Re: How can print a HTML file? <gellyfish@gellyfish.com>
    Re: How do you split a string into fixed sized pieces? <ltl@rgsun40.viasystems.com>
    Re: How do you split a string into fixed sized pieces? (Craig Berry)
    Re: Ignore the idiots <gellyfish@gellyfish.com>
    Re: in need of example... <gellyfish@gellyfish.com>
    Re: offtopic web transactions was [Re: What is best..?] <ltl@rgsun40.viasystems.com>
        perl whith nt and schedular <Manuel.Schicktanz@bmw.de>
    Re: problem with substitute op (s) (Craig Berry)
    Re: Pseudo Hashes (Damian Conway)
    Re: Reference challenge (Sean McAfee)
    Re: Reference challenge (Sean McAfee)
    Re: Reference challenge (Sean McAfee)
    Re: Reference challenge (Tramm Hudson)
    Re: Reference challenge <david@gigawatt.com>
    Re: Reference challenge (Sean McAfee)
    Re: Trim text <monty@primenet.com>
        WIn32::OLE <mwilliams@europarl.eu.int>
        Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)

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

Date: Fri, 22 Oct 1999 00:56:23 -0400
From: Amer Neely <aneely@softouch.on.ca>
Subject: Annoying file open problem
Message-Id: <380FEE77.F5DD2EE5@softouch.on.ca>

I'm writing a script to take input from a form and write it to a
separate file in my cgi-bin folder. This is for a simple message centre.
For some reason, I can't get my script to open a new file and write to
it. If the file exists, I can append to it, but for the life of me I
can't create a new one. I've run into this problem before, and gotten
around it by creating an empty file at home, then uploading it. I can
then append to it. I can't / don't want to do that with this script.

I'm naming the files incrementally, after getting the number of .dat
files in the directory. (1.dat, 2.dat, 3.dat ...)

The script in question works fine at home under Apache / Win95, but when
I u/l it to my site it quits working correctly.

The code snippet is:

# $numfiles is the number of .dat files in the directory
$postfile = ($numfiles + 1) . ".dat"; # create a file name
open (NEWPOST,">$postfile");
print NEWPOST "$datestr $timestr\n"; # these are already to go
print NEWPOST "$thissubject\n"; # from the form
print NEWPOST "$thisname\n\n"; # from the form
print NEWPOST "$thiscomment"; #from the form
close NEWPOST;

If anyone has any ideas as to why this is not working I would be forever
grateful. Once the file is created, I have no problem reading it.
-- 
Amer Neely aneely@softouch.on.ca
Certified Internet Webmaster Designer
Softouch Information Services: http://www.softouch.on.ca/
Research Central: http://www.softouch.on.ca/rc/
Member: HTML Writers Guild: http://www.hwg.org/
Member: Association of Web Professionals: http://www.a-w-p.org/


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

Date: Fri, 22 Oct 1999 05:40:22 GMT
From: pacman@defiant.cqc.com (Alan Curry)
Subject: Re: Annoying file open problem
Message-Id: <aNSP3.27579$E_1.1489260@typ11.nn.bcandid.com>

In article <380FEE77.F5DD2EE5@softouch.on.ca>,
Amer Neely  <aneely@softouch.on.ca> wrote:
>For some reason, I can't get my script to open a new file and write to
>it. If the file exists, I can append to it, but for the life of me I
>can't create a new one. I've run into this problem before, and gotten

>open (NEWPOST,">$postfile");

open() wants to tell you what is wrong, but you aren't listening to what it
has to say.

open(NEWPOST, ">$postfile") or die "$postfile: $!\n";

open() in void context should be a mandatory warning.
-- 
Alan Curry    |Declaration of   | _../\. ./\.._     ____.    ____.
pacman@cqc.com|bigotries (should| [    | |    ]    /    _>  /    _>
--------------+save some time): |  \__/   \__/     \___:    \___:
 Linux,vim,trn,GPL,zsh,qmail,^H | "Screw you guys, I'm going home" -- Cartman


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

Date: Fri, 22 Oct 1999 04:52:50 -0400
From: Amer Neely <aneely@softouch.on.ca>
To: Alan Curry <pacman@defiant.cqc.com>
Subject: Re: Annoying file open problem
Message-Id: <381025E2.32F5F2AE@softouch.on.ca>

Alan Curry wrote:
> 
> In article <380FEE77.F5DD2EE5@softouch.on.ca>,
> Amer Neely  <aneely@softouch.on.ca> wrote:
> >For some reason, I can't get my script to open a new file and write to
> >it. If the file exists, I can append to it, but for the life of me I
> >can't create a new one. I've run into this problem before, and gotten
> 
> >open (NEWPOST,">$postfile");
> 
> open() wants to tell you what is wrong, but you aren't listening to what it
> has to say.
> 
> open(NEWPOST, ">$postfile") or die "$postfile: $!\n";
> 
> open() in void context should be a mandatory warning.

Yes, I realize I should be doing that, as well as using strict and
diagnostics. However, for whatever reason, any of those options gets me
a '500 Internal server error'. And I don't have access to the server
logs.

This is all moot now, since I've solved my problem. I had forgotten I
was in a directory beneath cgi-bin, and neglected to turn on 'write'
privileges to it.

So, do I feel like two cents waiting for change? :)

Thanks for the response.
-- 
Amer Neely aneely@softouch.on.ca
Certified Internet Webmaster Designer
Softouch Information Services: http://www.softouch.on.ca/
Research Central: http://www.softouch.on.ca/rc/
Member: HTML Writers Guild: http://www.hwg.org/
Member: Association of Web Professionals: http://www.a-w-p.org/


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

Date: Fri, 22 Oct 1999 01:27:04 -0400
From: bob <bob>
Subject: Attn:  Perl/CGI wizards.  Your expertise is needed.  Simple Question?
Message-Id: <2=IPOL1eUUPX2vW7S0UkwSd6Rl9s@4ax.com>

I am writing a perl script that will take data from an html form and
write that info into an html file on my server, along with some html
prescripted in there for looks.  The purpose of the script is an easy
user updated web page for name, email, phone, etc. . .  Only a week
into learning Perl I was surprised that I managed to get this done and
actually have Perl write the file to the server.  That was the first
hitch.  Now, I would like to be able to have the user upload an image
file (their logo) through the web browser and save it to the local
server.  I could then have the script print the image link into the
web page to pull it up, no prob.  I would rather access the file
locally rather that remotely via a simple url.  Problem is I can't
figure out how to SAVE the binary file onto the local server.  Did it
with the form output for the html no sweat all text.  I found a small
script at:

  http://webreview.com/wr/pub/98/08/14/perl  

 This works great for getting the image up on the web and the script
is set up to immediately write the contents of the file back to the
browser, thus showing the file you just uploaded.  Great, but, it
doesn't save the file to the server.  I am currently working on this
bit of script separately from the rest of the form inputs for clarity,
but I'm sure I can integrate it back into the main script when I get
it worked out.  I have fooled around with the print command using the
file handler option like with the text file and have seen references
to binmode and chr functions and have even gotten so far as to have
the script create the file name entered in the form in the directory I
want on the local server but it fails to write the actual data into
the file.  Basically I get a blank file.  I have trudged through
countless FAQ's and documentations and such with no clear explanation
for this question.  Most of the documentation that I have read seems
to expect a pretty extensive knowledge of the language, therefore most
of it flies over my head.    I am only posting this here because I am
going blind reading perldoc this and that and not finding a well
explained solution.  So, based on the form and script above.  What is
the simplest, most straight forward way to write that binary file to
disk?  I don't care about printing a  results page, I don't need one
and I could do that myself.  I don't care how many milliseconds it
took to upload the file or the exact revision number of the poster's
web browser.  I just need the tiny bit of needle in a haystack code
that will extract whatever information it needs from the uploaded
binary data file and save it to the local server.  I will have a
rename function later that will name the file to what I want so it
doesn't have to check to see if a filename exists or anything.  I'm
just going to write over it anyway five lines down with a rename
function.  If anyone knows how this can be accomplished easier or more
efficiently please let me know.  Also please keep in mind that I will
be adding this to a bigger script if I ever get it to work.  I am open
to any suggestions on using a different method of getting the file
uploaded.   This script uses the CGI.pm module as you will see.  Sorry
to be so long winded but wanted to get the point across as clearly as
possible.    Please let me know if more info would help.  Yes I know
this is partly a CGI.pm question but who in the world uses it more
than Perl programmers?  And the part I am having a problem with is in
the actually in the perl code.

Also,  Please place your vote for the absolute best overall Perl
reference/training book.  Thanks.  


Regards, 

Bobby


Ready with the fire extinguisher.  ;)


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

Date: Fri, 22 Oct 1999 07:40:37 GMT
From: bblishA@TblackbeltDO.Tcom (Ben Blish)
Subject: Can I use flock as lever to create reliable unique cookie values?
Message-Id: <38100ffa.35270179@news.montanavision.net>


I am writing an application that needs to uniquely
ID visitors; I need to maintain a file with an
increasing unique code (a number is fine) for all
visitors.

This is probably comparable to a counter that
makes no errors, or a shopping cart ID, where
you *really* don't want to mix up carts between
your visitors.

I don't want to pester the users for personal info
or otherwise prod them on their privacy buttons, I
just need to know that the person on "this" page
is the same person who was on "that" page.

I have been scanning the perl docs, and it (kind of)
looks to me like I could do it with flock.

But the flock docs don't say what flock returns,
if anything, when an attempt to lock is made. Here's
pseudo code that (hopefully) describes what I want to
do with some imaginary functions (I have a C
background, please forgive...) Can I do essentially this
in PERL? If so, would someone provide me with the
conditional structure for calling flock?

I'd be just as happy with an open() call that ensured
that a particular program instance was the only instance
that could possible succeed in opening the file. Or
anything, in fact, that would give me a completely
reliable mechanism to maintain a local file as described.
Only my CGI will access this file, and only in the
manner shown in the pseudocode.

here's the pseudocode:

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

int mumble,watchdog;
filehandlething fht;

if (fht = fht_open(filename)) == NULL) { return(UNHAPPY1); }

mumble=1;
watchdog=0;
while(mumble)
 {
   if (fht_lock(fh,EXCLUSIVE_ACCESS)) /* if (succeeds) */
    {
      mumble=0; /* we have the file... can and will continue */
    }
   else /* (fails) */
    {
      watchdog++;
      if (watchdog > 30)
       {
        fht_close(fht);    /* release our unusable access to file... */
        return(UNHAPPY2);  /* ...took too many tries (30 concurrent users!?)*/
       }
      sleep(1,TIME_IN_SECONDS); /* sleep and try again in one second */
    }
 }

init_or_increment_file(fht);

fht_lock(fht,UNLOCK); /* release the exclusive lock */
fht_close(fht);       /* close file */

return(HAPPY);



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

Date: Thu, 21 Oct 1999 10:37:08 -0700
From: "Trent" <trent@jps.net>
Subject: Code example help?
Message-Id: <380f4f3e@news1.jps.net>

Gents, Ladies,

The code pasted below will open the desired directory, but unfortunately
will not read in the file contents... If the error is obvious to any of you,
please advise.

Thanks in advance,
Trent


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

# Filename and parameters from query
 $querystring = $ENV{'QUERY_STRING'};
 ($directory) = split(/\s*\,\s*/,$querystring,1);

 $directory = "../$directory";

 opendir(DIR,$directory);

 @files = grep(/\.asc/,readdir(DIR));



# HTML to put everything in
  print "Content-type: text/html\n\n";
      print "<HTML>\n";
      print "<HEAD><TITLE></TITLE></HEAD>\n";
      print "<BODY BGCOLOR=#FFFFFF TEXT=#000000 LINK=#0000FF ALINK=#0000FF
VLINK=#0000FF>\n";
      print "<CENTER>\n";
  print "<TABLE WIDTH=550 CELLPADDING=1 CELLSPACING=1 BORDER=0>\n";




 foreach $file(@files) {



 open(READ,$file);

 chop ($field_names = <READ>);
 @lines = <READ>;

 @lines = &sort_by_field(3, @lines);
 close(READ);



 foreach $line (@lines) {

 print"$line<br>\n";

     }




}







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

Date: Fri, 22 Oct 1999 05:31:30 GMT
From: cberry@cinenet.net (Craig Berry)
Subject: Re: Converting String To Upper and Lower Case
Message-Id: <s0vtlilcr0128@corp.supernews.com>

Brad Grove (brad.grove@hcn.com.au) wrote:
: I don't do enough PERL scripting to remember how to do this. Could someone
: please show me how to convert a string into upper and lower case at word
: breaks

If you mean find each \w-defined 'word' and convert it to initial cap,
lowercase all other characters:

  s/(\w+)/\u\L$1/g;

: and also just to convert the first character of a string to upper
: case.

perldoc -f ucfirst

-- 
   |   Craig Berry - cberry@cinenet.net
 --*--  http://www.cinenet.net/users/cberry/home.html
   |   "They do not preach that their God will rouse them
      a little before the nuts work loose." - Kipling


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

Date: 22 Oct 1999 09:51:18 +0100
From: Jonathan Stowe <gellyfish@gellyfish.com>
Subject: Re: How can print a HTML file?
Message-Id: <38102586_2@newsread3.dircon.co.uk>

Jing Shi <Jing.Shi@usa.alcatel.com> wrote:
> Will that print out the file with all the HTML tags?
> Yes, I can use HTML::Parse to get rid of those tags. But I mean
> how  I can get the print out just like I print it from Netscape?
> 

You may be able to find an HTML to Postscript filter or something like
that but this is not a Perl question - you should look perhaps at freshmeat
<http://freshmeat.net>

/J\
-- 
"I suggest you apply some lubrication before any bending begins" -
Antoine de Caunes, Eurotrash


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

Date: 22 Oct 1999 04:29:05 GMT
From: lt lindley <ltl@rgsun40.viasystems.com>
Subject: Re: How do you split a string into fixed sized pieces?
Message-Id: <7uop6h$5a4$1@rguxd.viasystems.com>

Neko <tgy@chocobo.org> wrote:
:>    @a = split /(?<=\G....)/s;

Oh, COOL!!!  When I first saw it I thought that it would bomb
on one of the end cases, but it doesn't.  I also thought
that a m//g modifier would be required to make the \G work,
but it is apparently implied by the split.

Nice job!  This would have been way down the list of attempts
I would have made.  


-- 
// Lee.Lindley   /// I used to think that being right was everything.
// @bigfoot.com  ///  Then I matured into the realization that getting
////////////////////   along was more important.  Except on usenet.


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

Date: Fri, 22 Oct 1999 05:18:39 GMT
From: cberry@cinenet.net (Craig Berry)
Subject: Re: How do you split a string into fixed sized pieces?
Message-Id: <s0vstfp0r0112@corp.supernews.com>

Scott Frazer (scott.frazer@ericsson.com) wrote:
: OK, I'm new to Perl and can't figure out how to split a long string
: into fixed sized pieces.  For example:
: 
: input -> "0123456789abcdef"
: output -> an array of "0123", "4567", "89ab", "cdef"

  @pieces = $input =~ m/(.{1,4})/sg;

I've set that up so it will give you any leftover characters in the last
element (so e.g. "123456" would produce ("1234", "56").  You can leave off
the '1,' part inside the curly braces *if* you either know your input
string will be a multiple of four chars long, or you want to throw away
leftover characters.

-- 
   |   Craig Berry - cberry@cinenet.net
 --*--  http://www.cinenet.net/users/cberry/home.html
   |   "They do not preach that their God will rouse them
      a little before the nuts work loose." - Kipling


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

Date: 22 Oct 1999 09:20:07 +0100
From: Jonathan Stowe <gellyfish@gellyfish.com>
Subject: Re: Ignore the idiots
Message-Id: <38101e37_2@newsread3.dircon.co.uk>

Greg Snow <snow@statsci.com> wrote:
>            here are some suggestions for getting positive rather than
> negative feedback:
> 
> * State you expertise, or lack thereof.  A statement like "I'm not an
> expert yet, but I think this will work"  
> 

I dont believe we want any stuff posted that people only 'think' might
work - if you dont 'know' it works dont post it - there are confused
newbies cutting and pasting broken cargo cult code as it is and I dont
think that we should do anything to make this worse.

/J\
-- 
"The most frightening thing on television since Anthea Turner revealed
she had a sister" - Suggs


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

Date: 22 Oct 1999 09:27:34 +0100
From: Jonathan Stowe <gellyfish@gellyfish.com>
Subject: Re: in need of example...
Message-Id: <38101ff6_2@newsread3.dircon.co.uk>

Erik van Roode <newsposter@cthulhu.demon.nl> wrote:
> Scratchie <AgitatorsBand@yahoo.com> wrote:
> 
>> Or just try 
> 
>>  my @graphics = `ls *.jpg *.gif`;
> 
>   Which only works if you happen to have a program 'ls' in your path
> that lists files. Even then, you get a newline after each filename
> that you have to filter out.
> 

But the original poster explicitly said that he was using Linux - which
last time I looked had a program ls in its path ...

The newline is trivially dealt with:

chomp(my @files = `ls *.jpg *.gif`);

Of course one generally would recommend using opendir/readdir but there's
no point in being dogmatic about it ...

/J\
-- 
"As usual I'm the price you have to pay for the funny bits" - Denis Norden


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

Date: 22 Oct 1999 04:10:02 GMT
From: lt lindley <ltl@rgsun40.viasystems.com>
Subject: Re: offtopic web transactions was [Re: What is best..?]
Message-Id: <7uoo2q$50r$1@rguxd.viasystems.com>

Abigail <abigail@delanet.com> wrote:
:>lt lindley (ltl@rgsun40.viasystems.com) wrote on MMCCXXXVII September
:>MCMXCIII in <URL:news:7u8kr5$1il$1@rguxd.viasystems.com>:
:>\\ What do the big sites do?  Maintain transaction state in their
:>\\ database for a fixed period of time and do garbage collection?

:>Hidden fields (probably the most reliable), cookies, URL codifying
:>(used to be more popular a few years ago), Javascript, Java, and
:>the attitude "screw them if it ain't works".

I just saw a post in c.l.p.a about a module to encrypt hidden CGI
fields.  This goes a long way to eliminate my confusion.  I read your
response and was incredulous that anyone would trust the data coming
back from the browser, but I was too afraid of my ignorance to ask
another question and look foolish.

The mere existence of the encryption module explains much.

Still, storing all of the state data with the client is so.. retro.:)

As I laugh about his dilemma of having to store the state
data with the client, I can't help but see that this
is the same problem we face(d) with CICS.  :-)

I know that this cannot be an original observation.   It is so
obvious that it must be a common joke somewhere.  It just isn't in my
line of sight.  But it is still funny, even if I am late to
discovering it.  :-)

-- 
// Lee.Lindley   /// I used to think that being right was everything.
// @bigfoot.com  ///  Then I matured into the realization that getting
////////////////////   along was more important.  Except on usenet.


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

Date: Fri, 22 Oct 1999 09:42:55 +0200
From: Manuel Schicktanz <Manuel.Schicktanz@bmw.de>
Subject: perl whith nt and schedular
Message-Id: <3810157F.6E4F5EA7@bmw.de>

Hi,

I use a perl-Script under NT.

It uses Win:OLE to start an Application, load some Files and at the end
I save the result.

It works fine.

BUT if I try to run my Script with the Schedular I can't Load the Files
(I use Absolut Path only).

What is wrong?

Regards

Manuel

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

Manuel Schicktanz
BMW AG, Ti-71
80788 München
Tel: +49 89 382 27982
Fax: +49 89 382 20425
Email: Manuel.Schicktanz@bmw.de
http://www.stadtplandienst.de/query;ORT=m;PLZ=80809;STR=Helene%2DMayer%2DRing;HNR=4





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

Date: Fri, 22 Oct 1999 05:26:35 GMT
From: cberry@cinenet.net (Craig Berry)
Subject: Re: problem with substitute op (s)
Message-Id: <s0vtcbb3r0111@corp.supernews.com>

iami@my-deja.com wrote:
: $_ = "-rw-rw-r--   1 root     ftp           230 Jul 22 16:36 tiff.README\n";
: 
: s/^.+[0-2][0-4]:[0-6][0-9]\040+//;
               ^ Hm?
The 1s-place digit of the hour can be 0-9; in your example above, for
instance, it's 6.  Therefore the line doesn't match the left-hand side of
the substitution, and no substitution occurs.

Also, why the use of octal 040 where a simple space or \s would be both
clearer and more portable; and why the minute 10s digit range topping at
6, when in fact 5 is the maximum?

-- 
   |   Craig Berry - cberry@cinenet.net
 --*--  http://www.cinenet.net/users/cberry/home.html
   |   "They do not preach that their God will rouse them
      a little before the nuts work loose." - Kipling


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

Date: 22 Oct 1999 05:54:17 GMT
From: damian@cs.monash.edu.au (Damian Conway)
Subject: Re: Pseudo Hashes
Message-Id: <7uou69$2q3$1@towncrier.cc.monash.edu.au>

"Scott Pritchett" <scott@salmon.ltd.uk> writes:

>> There is ample good coverage of pseudo hashes in Object Oriented Perl -
>> a good read! - or perldoc has info on this, if your version
>> supports this datatype.
>>
>I'm using 5.005_003 and I've just ordered that book coincidentally today.
>Can you tell me what I need to do to get it working in the meantime?

Well, since you bought my book, I suppose the least I can do is answer
your question :-)

A reference to an array can be treated like a reference to a hash if the
first element of the array holds a reference to a hash that maps keys
onto indices.  Such an array is known as a "pseudo-hash".

So:

    # 1. CREATE THE HASH THAT WILL MAP KEYS TO INDICES 

	$ref_to_hash = { beer => 1, snack => 2, logs => 3, last => 4 };

    # 2. CREATE AN ARRAY WITH A REFERENCE TO THE HASH IN ITS FIRST ELEMENT...

	$ref_to_array = [ $ref_to_hash, qw(Fosters Vegemite chainsaw supper) ];

    # 3. ACCESS ELEMENTS OF THE ARRAY AS IF IT WERE A HASH...

	print "G'day. D'ya wanna $ref_to_array->{beer} ",
	      "with yer $ref_to_array->{snack}, mate?\n"


Of course, you don't have to use anonymous arrays and hashes, so long
as you set up the references correctly:

    # 1. CREATE THE HASH THAT WILL MAP KEYS TO INDICES...

	%hash = ( beer => 1, snack => 2, logs => 3, last => 4 );

    # 2. CREATE AN ARRAY WITH A REFERENCE TO THE HASH IN ITS FIRST ELEMENT...

	@array = ( \%hash, qw(Fosters Vegemite chainsaw supper) );

    # 3. CREATE REFERENCE TO ARRAY...

	 $ref_to_array = \@array;

    # 4. ACCESS ELEMENTS OF THE ARRAY AS IF IT WERE A HASH...

	print "G'day. D'ya wanna $ref_to_array->{beer} ",
	      "with yer $ref_to_array->{snack}, mate?\n"


Hope this helps.

Damian


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

Date: Fri, 22 Oct 1999 05:15:03 GMT
From: mcafee@waits.facilities.med.umich.edu (Sean McAfee)
Subject: Re: Reference challenge
Message-Id: <rpSP3.351$4G.65915@news.itd.umich.edu>

In article <Pine.GSO.4.10.9910212309090.15158-100000@crusoe.crusoe.net>,
Jeff Pinyan  <japhy@pobox.com> wrote:
>On Oct 22, Sean McAfee blah blah blah:
>> Write a 100% Perl, 100% portable, 100% bulletproof subroutine that will
>> determine whether its single argument is a reference, and if so, what type
>> of reference it is.

>How is my regular expression,
>  ($type) = $obj =~ /([A-Z]+)\(0x[a-f0-9]+\)\z/;
>not valid as the subroutine?
>  sub trueref { (shift =~ /([A-Z]+)\(0x[a-f0-9]+\)\z/)[0] }

Because it fails if I pass it, say, the string "ARRAY(0xfffff)".

>> 1)  You may not call any functions which are not themselves 100% Perl, except
>> those described in the perlfunc man page.  This includes UNIVERSAL::isa().

>Is the regex a bad thing?

No, that's allowed.

-- 
Sean McAfee                                                mcafee@umich.edu
print eval eval eval eval eval eval eval eval eval eval eval eval eval eval
q!q@q#q$q%q^q&q*q-q=q+q|q~q:q? Just Another Perl Hacker ?:~|+=-*&^%$#@!


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

Date: Fri, 22 Oct 1999 05:18:04 GMT
From: mcafee@waits.facilities.med.umich.edu (Sean McAfee)
Subject: Re: Reference challenge
Message-Id: <gsSP3.352$4G.65898@news.itd.umich.edu>

In article <2vQP3.33$cV4.4160@nntp1>, Dave Kaufman <david@gigawatt.com> wrote:
>Dave Kaufman <david@gigawatt.com> wrote...
>> Sean McAfee <mcafee@waits.facilities.med.umich.edu> wrote...
>> > The challenge:
>> > Write a 100% Perl, 100% portable, 100% bulletproof subroutine that will
>> > determine whether its single argument is a reference, and if so, what type
>> > of reference it is.

>> The Solution:
>> sub isref {
>>     return ref{shift};
>> }

>oops -- i used curly braces instead of parens where neither was really
>needed... that's hardly bulletproof portable perl, eh?

>sub isref {
>    return ref shift;
>}

This fails if one passes it the expression 

bless [], "0"

Granted, this will almost never happen, but the challenge stipulated that
the solution be 100% bulletproof.

-- 
Sean McAfee                                                mcafee@umich.edu
print eval eval eval eval eval eval eval eval eval eval eval eval eval eval
q!q@q#q$q%q^q&q*q-q=q+q|q~q:q? Just Another Perl Hacker ?:~|+=-*&^%$#@!


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

Date: Fri, 22 Oct 1999 05:38:23 GMT
From: mcafee@waits.facilities.med.umich.edu (Sean McAfee)
Subject: Re: Reference challenge
Message-Id: <jLSP3.391$4G.66954@news.itd.umich.edu>

In article <380FCFE2.AFDE1B56@home.com>,
Rick Delaney  <rick.delaney@home.com> wrote:
>Sean McAfee wrote:
>> The challenge:
>> Write a 100% Perl, 100% portable, 100% bulletproof subroutine that will
>> determine whether its single argument is a reference, and if so, what type
>> of reference it is.
>> Conditions:
>... 
>> 2)  You may not use any implementation details of your particular version
>> of Perl.  If the manual states only that a given function returns FALSE
>> under certain circumstances, then you may not distinguish its return value
>> between the values undef, "", 0, and "0".

>Is this condition the one that rules out stringification as shown in the
>> thread entitled "Underlying data structure behind blessed reference".  
>?

No, stringification is fine.  I suppose the stringified form of a reference
is technically an implementation detail--at least, I can't find a
specification for the format of a stringified reference in a quick search
of the manual--but it seems to be a pretty constant feature across the
various versions of Perl 5, and in any case I'll allow it for the
challenge.

>I *think* this meets all your conditions, but I guess you need to be the
>judge of that.

Close, but like the simple

>sub isref {
>    return ref shift;
>}

posted elsewhere, your solution fails for the expression

bless [], "0"

>#!/usr/local/bin/perl -w
>use strict;
>
>my $scalar = bless \$a       => 'ARRAY';
>my $array  = bless [1, 2]    => 'HASH';
>my $hash   = bless {1 => 2}  => 'GLOB';
>my $glob   = bless \*STDOUT  => 'CODE';
>my $code   = bless sub { 1 } => 'SCALAR';
>
>BEGIN {
>    my %text = (
>        '$' => 'SCALAR',
>        '@' => 'ARRAY',
>        '%' => 'HASH',
>        '*' => 'GLOB',
>        '&' => 'CODE',
>    );
>    
>    sub reference ($) {
>        my $ref = shift;
>        return unless ref $ref;
>
>        for (qw/* $ @ %/) {
>            eval "$_\$ref";
>            if ($@ !~ /Not an? $text{$_} reference/) {
>                return $text{$_};
>            }
>        }
>        return $text{'&'};
>    }
>}
>
>for ($scalar, $array, $hash, $glob, $code, ) {
>    print "Here be ", reference $_, " ref\n";
>}

-- 
Sean McAfee                                                mcafee@umich.edu
print eval eval eval eval eval eval eval eval eval eval eval eval eval eval
q!q@q#q$q%q^q&q*q-q=q+q|q~q:q? Just Another Perl Hacker ?:~|+=-*&^%$#@!


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

Date: 21 Oct 1999 23:15:32 -0600
From: hudson@swcp.com (Tramm Hudson)
Subject: Re: Reference challenge
Message-Id: <7uortk$3lm@llama.swcp.com>

[posted and cc'd to cited author]

Rick Delaney  <rick.delaney@home.com> wrote:
 ...
> I *think* this meets all your conditions, but I guess you need to be the
> judge of that.

Your code also works on several of the test cases that I designed, although
it does fail on this one:

{
        package Foo;
        use base 'Tie::Scalar';
        sub TIESCALAR { bless {} }
        sub FETCH { "Baz" }
}

my $foo;
tie $foo, 'Foo';

Your code reports that $foo is a "Here be  reference".  Not quite
what I would expect.  It does properly handle ones that try to trick it
like this:

{
        package Bar;
        use overload '""' => sub { 'ARRAY' };
}

my $bar = bless {}, 'Bar';

since the eval statement doesn't call the stringification
operator.  Sneaky!

Good job,
Tramm
-- 
  o   hudson@swcp.com                 tbhudso@cs.sandia.gov   O___|   
 /|\  http://www.swcp.com/~hudson/          H 505.323.38.81   /\  \_  
 <<   KC5RNF @ N5YYF.NM.AMPR.ORG            W 505.284.24.32   \ \/\_\  
  0                                                            U \_  | 


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

Date: Fri, 22 Oct 1999 01:52:13 -0400
From: "Dave Kaufman" <david@gigawatt.com>
Subject: Re: Reference challenge
Message-Id: <hYSP3.41$cV4.5358@nntp1>

Sean McAfee <mcafee@waits.facilities.med.umich.edu> wrote ...
> >Dave Kaufman <david@gigawatt.com> wrote...
> >> Sean McAfee <mcafee@waits.facilities.med.umich.edu> wrote...
> >> > The challenge:
> >> > Write a 100% Perl, 100% portable, 100% bulletproof subroutine that
will
> >> > determine whether its single argument is a reference, and if so, what
type
> >> > of reference it is.
>
> >sub isref {
> >    return ref shift;
> >}
>
> This fails if one passes it the expression
>
> bless [], "0"
>
> Granted, this will almost never happen, but the challenge stipulated that
> the solution be 100% bulletproof.
>


okay, i guess if one puts garbage in and *still* wont tolerate garbage
out... how about:

sub isref {
        return defined $_[0] ? ref $_[0]: undef;
}

if you try real hard you still *might* be able to get this to return a
*false* value, but it will always return a *defined* value for a reference
(the type) and undef for a non-reference, i do believe.  so you'd want to
test the definedness of the return, to be totally teflon.

-dave




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

Date: Fri, 22 Oct 1999 06:24:52 GMT
From: mcafee@waits.facilities.med.umich.edu (Sean McAfee)
Subject: Re: Reference challenge
Message-Id: <UqTP3.398$4G.67527@news.itd.umich.edu>

In article <hYSP3.41$cV4.5358@nntp1>, Dave Kaufman <david@gigawatt.com> wrote:
>Sean McAfee <mcafee@waits.facilities.med.umich.edu> wrote ...
>> >Dave Kaufman <david@gigawatt.com> wrote...
>> >sub isref {
>> >    return ref shift;
>> >}

>> This fails if one passes it the expression
>> bless [], "0"

>okay, i guess if one puts garbage in and *still* wont tolerate garbage
>out...

I wouldn't call valid Perl "garbage", myself...

>how about:

>sub isref {
>        return defined $_[0] ? ref $_[0]: undef;
>}

>if you try real hard you still *might* be able to get this to return a
>*false* value, but it will always return a *defined* value for a reference
>(the type) and undef for a non-reference, i do believe.  so you'd want to
>test the definedness of the return, to be totally teflon.

Try this:

sub isref { return defined $_[0] ? ref $_[0]: undef; }
print defined isref(5);

I get "1" on my system.

I don't know why I neglected to mention it in my first followup, but by
"determine the type of the reference" what I meant was "determine if it is
a scalar, array, hash, code, or glob reference", not "determine the type of
the reference if it is unblessed, or the package it has been blessed into
if it is blessed", which is what ref() does.  isref(bless [], "HASH")
returns "HASH".

-- 
Sean McAfee                                                mcafee@umich.edu
print eval eval eval eval eval eval eval eval eval eval eval eval eval eval
q!q@q#q$q%q^q&q*q-q=q+q|q~q:q? Just Another Perl Hacker ?:~|+=-*&^%$#@!


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

Date: 22 Oct 1999 08:43:19 GMT
From: Jim Monty <monty@primenet.com>
Subject: Re: Trim text
Message-Id: <7up837$o74$1@nnrp03.primenet.com>

sushi38@my-deja.com wrote:
> open (Lastquake, ">lastquake.txt") || die "Can't open quake.txt for
> writing! $!\n";

And here you have a vestigual cut 'n' paste bug in your error message.
Use a variable to avoid confounding the poor user (or the poor
programmer!):

  my $file = 'lastquake.txt';
  open LASTQUAKE, ">$file" or die "Can't open $file for writing: $!\n";

-- 
Jim Monty
monty@primenet.com
Tempe, Arizona USA


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

Date: Fri, 22 Oct 1999 09:32:05 +0200
From: "williams, mark" <mwilliams@europarl.eu.int>
Subject: WIn32::OLE
Message-Id: <RhMPOMC2h4RLOTa8kHG6XqBBqiDi@4ax.com>

I would like to use Excel for something like this  

(Neat but does not work)

	$Sheet->Range("A1")->{WorksheetFunction.Sum}= 'B1:B499';

But I don't know where to look VBfor Applications has it 

This is not  neat but works

	$Sheet->Range("A1")->{Value}= "=SUM(R[1]C[1]:R[499]C[1])";

Any Ideas

Wilf Williams
http://members.tripod.com/williams_mr
The Opinions expessed are my own (I don't have an employer!)


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

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


Administrivia:

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

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

| NOTE: The mail to news gateway, and thus the ability to submit articles
| through this service to the newsgroup, has been removed. I do not have
| time to individually vet each article to make sure that someone isn't
| abusing the service, and I no longer have any desire to waste my time
| dealing with the campus admins when some fool complains to them about an
| article that has come through the gateway instead of complaining
| to the source.

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

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

For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V9 Issue 1148
**************************************


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