[19360] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 1555 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Aug 17 21:06:02 2001

Date: Fri, 17 Aug 2001 18:05:08 -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: <998096708-v10-i1555@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Fri, 17 Aug 2001     Volume: 10 Number: 1555

Today's topics:
    Re: capitalisation/DBD/mysql (Martien Verbruggen)
    Re: capitalisation/DBD/mysql <bart.lateur@skynet.be>
        FAQ: Why doesn't glob("*.*") get all the files? <faq@denver.pm.org>
        Getting text from a document <lmoran@wtsg.com>
    Re: Getting text from a document <krahnj@acm.org>
    Re: Help with Piped command, capturing output <mbudash@sonic.net>
    Re: Help!  Multiple line extract from file based on use <cberry@cinenet.net>
    Re: Help!  Multiple line extract from file based on use <joe+usenet@sunstarsys.com>
    Re: IO::Socket::INET - Setting Reset bit when closing T <bkennedy99@Home.com>
    Re: local exec via cgi (David Efflandt)
        Local Perl via browser <skashani@uk.ibm.com>
        MySQL bug <smarx@i2000.com>
    Re: newbie regexp question <krahnj@acm.org>
    Re: Perl OO needs the opposite of SUPER:: (Martien Verbruggen)
    Re: Perl OO needs the opposite of SUPER:: (Martien Verbruggen)
    Re: Perl OO needs the opposite of SUPER:: (Martien Verbruggen)
    Re: Perl OO needs the opposite of SUPER:: <ren@tivoli.com>
    Re: Processing a scalar in the same way of a filehandle <bart.lateur@skynet.be>
    Re: Processing a scalar in the same way of a filehandle <bart.lateur@skynet.be>
        redirecting stdin and stdout <tarak@lectura.CS.Arizona.EDU>
    Re: regexp question with no answer yet <bart.lateur@skynet.be>
        removing trailing and leading blanks <nospam@newsranger.com>
    Re: Searching Text File <krahnj@acm.org>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Sat, 18 Aug 2001 08:00:59 +1000
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: capitalisation/DBD/mysql
Message-Id: <slrn9nr50r.3ga.mgjv@martien.heliotrope.home>

On 17 Aug 2001 14:39:45 +0400,
	Ilya Martynov <ilya@martynov.org> wrote:
> 
> PF> DBI-> install_driver('mysql'); OR
> PF> DBI-> connect(DBI:mysql:database=d;hostname=localhost);
> 
> It should be 
> 
> DBI-> connect('dbi:mysql:database=d;hostname=localhost');

$ man DBD::mysql
[SNIP]
           use DBI;

           $driver = "mSQL"; # or "mSQL1";
           $dsn = "DBI:$driver:database=$database;host=$hostname";

           $dbh = DBI->connect($dsn, undef, undef);

               or

           $driver = "mysql";
           $dsn = "DBI:$driver:database=$database;host=$hostname;port=$port";

           $dbh = DBI->connect($dsn, $user, $password);
[SNIP]

Do you want to send them a bug report? :)

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | life ain't fair, but the root
Commercial Dynamics Pty. Ltd.   | password helps. -- BOFH
NSW, Australia                  | 


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

Date: Sat, 18 Aug 2001 00:11:26 GMT
From: Bart Lateur <bart.lateur@skynet.be>
Subject: Re: capitalisation/DBD/mysql
Message-Id: <1ocrntk24opg3rn4iqchr21ns15n2ei8bq@4ax.com>

Helgi Briem wrote:

>>    DBI->connect(DBI:mysql:database=d;hostname=localhost);
>>
>That however doesn't [work].  It produces an error:
>syntax error at script line 5, near "DBI:"
>syntax error at script line 5, near "localhost)"

Of course, the whole parameter bunch should be one string, i.e., quoted.

    DBI->connect("DBI:mysql:database=d;hostname=localhost");

-- 
	Bart.


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

Date: Sat, 18 Aug 2001 00:17:01 GMT
From: PerlFAQ Server <faq@denver.pm.org>
Subject: FAQ: Why doesn't glob("*.*") get all the files?
Message-Id: <1uif7.222$V3.170764800@news.frii.net>

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with every Standard Distribution of
Perl.

+
  Why doesn't glob("*.*") get all the files?

    Because even on non-Unix ports, Perl's glob function follows standard
    Unix globbing semantics. You'll need "glob("*")" to get all (non-hidden)
    files. This makes glob() portable even to legacy systems. Your port may
    include proprietary globbing functions as well. Check its documentation
    for details.

- 

Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short.  They represent an important
part of the Usenet tradition.  They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile.  If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Answers to questions about LOTS of stuff, mostly not related to
Perl, can be found by pointing your news client to

    news:news.answers

or to the many thousands of other useful Usenet news groups.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release.  It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.

  AUTHOR AND COPYRIGHT

    Copyright (c) 1997-1999 Tom Christiansen and Nathan
    Torkington.  All rights reserved.

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.

                                                           05.32
-- 
    This space intentionally left blank


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

Date: Fri, 17 Aug 2001 18:38:27 -0400
From: Lou Moran <lmoran@wtsg.com>
Subject: Getting text from a document
Message-Id: <596rnt8mihlvbv5vl0g1hpjchef1ses7vm@4ax.com>

I have written the following script:  (I meant to use Net-Ping but I
didn't have time to read its docs) (and I run this on linux boxes
occasionally so that's the shebang and yes I change the -n to a -c) 

#!/usr/bin/perl -w

use strict ;
use diagnostics ;
use LWP::Simple ;

#this will run a ping to our firewall
#to yahoo.com
#to 132.163.4.101 an NIST Time Server
#and with get the time (UTC)
#run this script piped to text from the prompt

my $ping1 = (`ping XXX.XXX.XXX.XXX -n 1`) ;
my $ping2 = (`ping yahoo.com -n 25`) ;
my $ping3 = (`ping 132.163.4.101 -n 25`) ;           
my $numb  = 51 ;

until ($numb == 1) {
     chomp $numb ;
     $numb -- ;
     
     print "R---------------------------\n" ;
     print $ping1 ;
     print "Y---------------------------\n" ;
     print $ping2 ;
     print "I---------------------------\n" ;
     print $ping3 ;
     print "T---------------------------\n" ;
     getprint "http://132.163.4.101:13 \n" ;
     print "E---------------------------\n" ;
}



It produces this output: (edited for content!)

P---------------------------

Pinging XXX.XXX.XXX.XXX with 32 bytes of data:

Reply from XXX.XXX.XXX.XXX: bytes=32 time<10ms TTL=63

Ping statistics for XXX.XXX.XXX.XXX:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum =  0ms, Average =  0ms
P---------------------------

Pinging yahoo.com [216.115.108.245] with 32 bytes of data:

Reply from 216.115.108.245: bytes=32 time=70ms TTL=237
 ...
Reply from 216.115.108.245: bytes=32 time=90ms TTL=237

Ping statistics for 216.115.108.245:
    Packets: Sent = 25, Received = 25, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 70ms, Maximum =  90ms, Average =  72ms
P---------------------------

Pinging 132.163.4.101 with 32 bytes of data:

Reply from 132.163.4.101: bytes=32 time=90ms TTL=39
 ...
Reply from 132.163.4.101: bytes=32 time=111ms TTL=39

Ping statistics for 132.163.4.101:
    Packets: Sent = 25, Received = 25, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 90ms, Maximum =  111ms, Average =  92ms
T---------------------------

52138 01-08-17 22:08:06 50 0 0 404.0 UTC(NIST) * 
T---------------------------




I would like the final output to look like this:

Reply from XXX.XXX.XXX.XXX: bytes=32 time<10ms TTL=63

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

Reply from 216.115.108.245: bytes=32 time=70ms TTL=237
 ...
Reply from 216.115.108.245: bytes=32 time=90ms TTL=237
Average =  72ms

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

Reply from 132.163.4.101: bytes=32 time=90ms TTL=39
 ...
Reply from 132.163.4.101: bytes=32 time=111ms TTL=39
Average =  92ms

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

52138 01-08-17 22:08:06 50 0 0 404.0 UTC(NIST) * 

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

I pipe the output to text in a file called (imaginatively) ping.txt so
I am thinking that I should write another script to pull the info I
want out.  Or possibly do some sort of manipulation at the end of the
until loop?

This is one of those case where I know exactly what I want and have NO
IDEA how to get it.

any ideas? pointers? perldocs? how would you do it?


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

Date: Fri, 17 Aug 2001 23:53:52 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: Getting text from a document
Message-Id: <3B7DAEF1.95550581@acm.org>

Lou Moran wrote:
> 
> I have written the following script:  (I meant to use Net-Ping but I
> didn't have time to read its docs) (and I run this on linux boxes
> occasionally so that's the shebang and yes I change the -n to a -c)
> 
> [snip code]
> 
> It produces this output: (edited for content!)
> 
> [snip output]
> 
> I pipe the output to text in a file called (imaginatively) ping.txt so
> I am thinking that I should write another script to pull the info I
> want out.  Or possibly do some sort of manipulation at the end of the
> until loop?
> 
> This is one of those case where I know exactly what I want and have NO
> IDEA how to get it.
> 
> any ideas? pointers? perldocs? how would you do it?


#!/usr/bin/perl -w

use strict;
use diagnostics;
use LWP::Simple;

#this will run a ping to our firewall
#to yahoo.com
#to 132.163.4.101 an NIST Time Server
#and with get the time (UTC)
#run this script piped to text from the prompt

my @ping1 = grep /^Reply from / or s/.*(Average\s+=\s+\d+ms\s*)/$1/,
`ping XXX.XXX.XXX.XXX -n 1`;
my @ping2 = grep /^Reply from / or s/.*(Average\s+=\s+\d+ms\s*)/$1/,
`ping yahoo.com -n 25`;
my @ping3 = grep /^Reply from / or s/.*(Average\s+=\s+\d+ms\s*)/$1/,
`ping 132.163.4.101 -n 25`;

for ( 1 .. 50 ) {
    print "R---------------------------\n";
    print @ping1;
    print "Y---------------------------\n";
    print @ping2;
    print "I---------------------------\n";
    print @ping3;
    print "T---------------------------\n";
    getprint "http://132.163.4.101:13 \n";
    print "E---------------------------\n";
    }

__END__


John
-- 
use Perl;
program
fulfillment


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

Date: Fri, 17 Aug 2001 23:18:59 GMT
From: Michael Budash <mbudash@sonic.net>
Subject: Re: Help with Piped command, capturing output
Message-Id: <mbudash-060499.16190617082001@news.sonic.net>

In article <4d6fd5fc.0108171155.126a57ae@posting.google.com>, 
dawfun@seanet.com (Jonathan Cunningham) wrote:

> Here's my little program called myPGP.pl running on W2k:
> 
>    use strict;
> 
>    my $passphrase = shift;
>    my $pubKey = shift;
>    my $message = shift;
> 
>    open(OUTPUT,"|pgp -feast -m -z $passphrase $pubKey");
>    print OUTPUT $message;
>    close OUTPUT;
> 
>    print "\n\nDONE\n";
> 
> I call this program from the command line, and pass to it my PGP
> password, public key, and the message I want to encrypt (as a glob of
> text).
> 
> For example:
> 
>    perl -w myPGP.pl password someKey@someDomain.com "Encrypt this
> text"
> 
> This does about 98% of what I'm trying to do, which is to pass text to
> PGP and encrypt it.  When this is run all output is printed to the
> screen (STDOUT), including the encrypted message.  This is fabulous,
> however I'd also (or alternatively) like to capture the output to a
> variable within this program and then do something else to it (TBD).
> 
> I've tried using open2() to do the bidirectional pipe thing, but that
> left me thoroughly confused, and didn't even work.  :P  I've also
> tried other things like using the pipe() function, but never made any
> sense out of that either.

open2 is the way. here's a snippet to get you started:

# We need a library function
   use IPC::Open2;

# Set up the pgp command
  $pgpcmd = "/full/path/to/pgp -feast -m -z $passphrase $pubKey";

# Open the PGP program for bidirectional I/O
   $pid = open2(\*READPGP, \*WRITEPGP, $pgpcmd) or die("oops!: $!");

# Send data to be encrypted to PGP
   print WRITEPGP $text_to_encrypt;

# Encrypt the data
   close(WRITEPGP);

# Get the encrypted data from PGP
   $encrypted_text = do { local $/; <READPGP> };
   close(READPGP);

hth-
-- 
Michael Budash ~~~~~~~~~~ mbudash@sonic.net


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

Date: Sat, 18 Aug 2001 00:12:02 -0000
From: Craig Berry <cberry@cinenet.net>
Subject: Re: Help!  Multiple line extract from file based on user input.
Message-Id: <Xns9100AEF9A794Bcberrycinenetnet1@207.126.101.92>

Joe Schaefer <joe+usenet@sunstarsys.com> wrote in 
news:m3d75u2w39.fsf@mumonkan.sunstarsys.com:

> Craig Berry <cberry@cinenet.net> writes:
> 
>> Problem is that this loses the ability to select lines in arbitrary 
>> order like "12,9".  Doing that without slurping the file is tough. 
> 
> Golf?
> 
> % perl -pe '@b[grep{$.==$a[$_]}0..$#a]=($_)x@a}BEGIN{$_=shift;
>             s/-/../g;@a=eval}for(@b){'  <string> <file>

I can't even come close.  Very cool.  I'll be interested to see if anyone 
else can outdo it...


-- 
Craig Berry <http://www.cinenet.net/~cberry/>
"That which is now known, was once only imagined." - William Blake



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

Date: 17 Aug 2001 20:19:16 -0400
From: Joe Schaefer <joe+usenet@sunstarsys.com>
Subject: Re: Help!  Multiple line extract from file based on user input.
Message-Id: <m38zgi2pa3.fsf@mumonkan.sunstarsys.com>

Joe Schaefer <joe+usenet@sunstarsys.com> writes:

> Golf?
> 
> % perl -pe '@b[grep{$.==$a[$_]}0..$#a]=($_)x@a}BEGIN{$_=shift;
>             s/-/../g;@a=eval}for(@b){'  <string> <file>

Better, and one shorter- follows Brendon's approach:

  % perl -pe 'exists$h{$.}and$h{$.}=$_}BEGIN{$_=shift;s/-/../g;
              \@h{@a=eval}}for(@h{@a}){'  <string> <file>
-- 
Joe Schaefer         "Experience is one thing you can't get for nothing."
                                               -- Oscar Wilde



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

Date: Sat, 18 Aug 2001 00:57:48 GMT
From: "Ben Kennedy" <bkennedy99@Home.com>
Subject: Re: IO::Socket::INET - Setting Reset bit when closing TCP connection?
Message-Id: <g4jf7.113915$EP6.29935572@news1.rdc2.pa.home.com>


"Jay McGavren" <sgarfunkle@hotmail.com> wrote in message
news:6bb557e1.0108171020.38c5016f@posting.google.com...

> How can I specify that I want the 'Fin' bit off and the Reset bit on,
> hopefully while still using IO::Socket::INET?  Many thanks for any
> help you can give!

Unless you want to reimplement a TCP stack with raw sockets, you can't munge
packets like this in Perl - perhaps you just need to use the shutdown()
command on the socket?

--Ben Kennedy




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

Date: Fri, 17 Aug 2001 23:43:13 +0000 (UTC)
From: see-sig@from.invalid (David Efflandt)
Subject: Re: local exec via cgi
Message-Id: <slrn9nrb0g.38i.see-sig@typhoon.xnet.com>

On Fri, 17 Aug 2001 09:31:27 -0700, Jürgen Exner <jurgenex@hotmail.com> wrote:
> "GunneR" <ds@ss.com> wrote in message
> news:129rntscc67ecs5cm8hehf82cpet5618fi@4ax.com...
>> I know this is very insecure, and im not sure if its even perl
>> related, but...
> No, your are right: this has nothing to do with Perl
> 
>> Im trying to write a cgi script that executes local code (via system,
>> exec, etc) on the system that visits the page.
> 
> Let me get this straight:
> - The Perl script is running as a CGI program on the web server
> - You want this script to start/run some program on the client
> 
> Luckily this is not possible! It would be a security hole as large as
> Alaska.
> Just imagine you are visiting my web site and my CGI script would run a
> "format" on your computer....

Huh, what kind of systems have you been on.  Perl CGI can run external
commands, scripts or programs just like any other Perl script can,
provided the user that CGI is running as has permission to do that.  A
normal user would (hopefully) not have permission to format a drive.

You simply use backticks if you want to capture output in your script, 
system() if you want output to go to Perl's STDOUT (you cannot capture 
it), or exec() if you want to execute something and never return (script 
is over at that point).  No special modules are required.

However, it you want something to remain running after the CGI terminates, 
you would have to daemonize it (look for daemonize in perldoc perlipc).

-- 
David Efflandt  (Reply-To is valid)  http://www.de-srv.com/
http://www.autox.chicago.il.us/  http://www.berniesfloral.net/
http://cgi-help.virtualave.net/  http://hammer.prohosting.com/~cgi-wiz/


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

Date: Fri, 17 Aug 2001 12:20:46 +0100
From: "Shah Kashani" <skashani@uk.ibm.com>
Subject: Local Perl via browser
Message-Id: <9liuko$nfi$1@sp15at20.hursley.ibm.com>

Hi guys,
Just a rather stupid question; is it possible to run perl files locally in a
browser? I write quite a lot of Perl stuff for the web, and every time I
want to test them, I have to keep uploading them. Don't wanna do that. Any
ideas?

Cheers,
Shah






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

Date: Fri, 17 Aug 2001 20:16:47 -0400
From: "Steve" <smarx@i2000.com>
Subject: MySQL bug
Message-Id: <8tif7.46$Y3.1725@newsreader.i-2000.net>

the problem described below appears to be a MySQL, not a perl, problem.
nonetheless i am hoping that someone in this group can help.
I am using Perl DBI to interface with MySQL and when i execute the
following statement:
$dbh = DBI->connect('DBI:mysql:database=dbmysql2', undef, undef,
{PrintError =>0}) || die $ DBI::errstr;
it causes the error:
[Fri Aug 17 09:59:50 2001] productioncontent14.pl: Access denied for user:
'@localhost'
to database 'dbmysql2' at productioncontent14.pl line 29, <STDIN> line 1

the dbi connect is being invoked by a perl program which is run from the
command line.

when i execute the above DBI->connect statement with my MySQL userid and
password it works fine.
i have MySQL (not unix) root level privileges. for performance and
security reasons i prefer to execute the version of the connect which is
failing.

i am running MySQL as described below:
Server version 3.23.36
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/lib/mysql/mysql.sock

i am running Perl 5.6 and Red Hat 7.1 Linux 2.4.3-12
i checked that i have access to mysql.sock

in addition to a my local host with my user name which is fully
privileged, i currently show local host with no user name and no password
in the mysql user table and with no privileges. i tried, as mysql root, to
grant all privileges to localhost, which has no user name, via the sql
command:
grant all privileges on *  to "%@localhost";
this resulted in a user table entry of no host name, a user name of
"%@localhost" and no privileges. this didn't seem useful so i deleted the
new user name, "%localhost" from all of the mysql security tables.








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

Date: Fri, 17 Aug 2001 22:26:40 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: newbie regexp question
Message-Id: <3B7D9A78.5C1568BD@acm.org>

Tassos Chatzithomaoglou wrote:
> 
> $string = [1.2.3.4.5.6];
> 
> $string =~ s/[\[\]]//g;
> @string_temp = split(/\./,$string);
> $string = join(".", $string_temp[0],$string_temp[1],$string_temp[2],$string_temp[3]);
> 
> print "str=$string\n";
> 
> desired output
> --------------
> str=1.2.3.4
> 
> I'm sure someone will have a cleverer idea....


my $string = '[1.2.3.4.5.6]';

$string =~ s/\[(\d+\.\d+\.\d+\.\d+).*/$1/;

print "str=$string\n";



John
-- 
use Perl;
program
fulfillment


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

Date: Sat, 18 Aug 2001 08:05:52 +1000
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Perl OO needs the opposite of SUPER::
Message-Id: <slrn9nr5a0.3ga.mgjv@martien.heliotrope.home>

On Thu, 16 Aug 2001 10:43:57 +0200,
	Tassilo von Parseval <Tassilo.Parseval@post.rwth-aachen.de> wrote:
> 
>                              Base-classes are most often abstract so you 
> can't sensibly instantiate one.

I don't think this is true, and my problem is with the word 'most' in
the above sentence. Base classes may often be abstract (or for Perl,
meant to be abstract), but they certainly are not in most cases.  Any
time you need to have a class that behaves differently from one that you
already have, you can subclass it, and override one or more of its
methods. The original class can be a fully functional class, and very
often is.

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | I took an IQ test and the results
Commercial Dynamics Pty. Ltd.   | were negative.
NSW, Australia                  | 


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

Date: Sat, 18 Aug 2001 08:17:59 +1000
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Perl OO needs the opposite of SUPER::
Message-Id: <slrn9nr60n.3ga.mgjv@martien.heliotrope.home>

On Thu, 16 Aug 2001 11:26:25 -0400,
	brian d foy <comdog@panix.com> wrote:
> In article <a73bcad1.0108160019.2d7b9b81@posting.google.com>, 
> johnlin@chttl.com.tw (John Lin) wrote:
> 
>> I encounter a problem and figured out that for Perl OO, we need
>> an expression which is opposite to SUPER::  (let's say VIRTUAL::)

>> When I designed a Base class, in Base::init() I want to call the
>> inheritor-class's init().

> if this is not what you want to happen, and you want the
> base class's init() called first (but why would you have
> overridden a method you didn't really want to override?),
> then you can simply not override the method.  the derived
> classes will have some other method name that the
> base class expects.
> 
>     #!/usr/bin/perl
> 
>     package MyBase;
> 
>     sub new { bless [], shift }
> 
>     sub init 
>         { 
>         print "This is MyBase::Init\n"; 
>         $_[0]->_init; 
>         print "MyBase::Init again\n" 
>         }

And if you insert this here:

    sub _init {}

or even

    sub _init { croak "_init has to be defined" }

then the problem should be solved, unless I'm still missing something.

>     package MyDerived;
> 
>     @ISA = qw(MyBase);
> 
>     sub _init { print "MyDerived::Init was called\n" }

This problem doesn't require the parent class to know anything about the
inheriting classes. All it needs to do is proscribe the presence of a
_init() method. In other languages that can be done with interface
specifications. In Perl, the easiest way is to provide that methos
yourself as well, and just have it do nothing, or throw an error.

As far as I can tell, the OP is asking how he can be sure that a child
class has a method that he can call directly. The normal solution in OO
is as described above. In Perl, you can be a bit more devious, and not
proscribe anything. Then at runtime, you check whether it can be done:

     sub init 
     { 
         print "This is MyBase::Init\n"; 
         $_[0]->_init if $_[0]->can("_init");
         print "MyBase::Init again\n" 
     }

From a post downthread I noticed that the OP needs this functionality to
be able to cal the child classes initialisation routine between two
blocks of statements in the base classes initialisation routine. This
may very well be true, but it doesn't justify throwing over years of OO
wisdom that a base class categorically doesn't ever want to know about
its inherited child classes. I'd suggest using the approach brian d foy
gave you, or rethinking the design of your base class.

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | I'm just very selective about what I
Commercial Dynamics Pty. Ltd.   | accept as reality - Calvin
NSW, Australia                  | 


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

Date: Sat, 18 Aug 2001 08:49:21 +1000
From: mgjv@tradingpost.com.au (Martien Verbruggen)
Subject: Re: Perl OO needs the opposite of SUPER::
Message-Id: <slrn9nr7rh.3ga.mgjv@martien.heliotrope.home>

On 17 Aug 2001 08:35:01 -0700,
	John Lin <johnlin@chttl.com.tw> wrote:

[snip of case]

> Now ExtendedReport inherits Report and tries to change the behavior of
> "sub report", so it must be named "sub ExtendedReport::report".
> 
> But "ExtendedReport::report" will not be called at all
> because "OddReport::report" (or "EvenReport::report") exists.
> 
> To solve the problem, I have to rename all the inheritor-class's "sub report"
> into "sub _report".  Otherwise I have to re-write the base class Report.

Note that all of this renaming is a result of the fact that you had a
class (and inhertance tree) design, and you are now changing it by
changing the inheritance pattern. This always gets messy. Maybe you
should take a step back, forget about the classes you already have, and
design them from scratch, and then change your current set of classes to
accomodate that design.

A design using abstract methods:

Report:
    provides new(), gen()
    requires (abstract) report()

ExtendedReport <- Report
    provides report()
    requires (abstract) bare_report()

EvenReport <- ExtendedReport
    provides bare_report()

OddReport  <- ExtendedReport
    provides bare_report()

This is almost identical to the renaming stuff, and indeed, not too
elegant.

An alternative design, which doesn't require changing the classes, but
requires the caller to change their behaviour:

Report:
    provides new() gen()
    requires report()

ExtendedReport <- Report
    provides counted_report() (which calls $self->report)

EvenReport <- ExtendedReport
    provides report()

OddReport  <- ExtendedReport
    provides report()

Not great, because now the caller needs to decide which report they
want, and I suspect that's not what you want. This last one could also
be done with multiple inheritance.

But I think there is a better design, which will make future changes
9other report formats) easier to deal with as well:

To go back to ExtendedReport::report() for a minute:

> sub report {
>     my $self = shift;
>     print "NOTE: every report will add element counting.\n";
>     $self->_report;
>     print "There are @{[scalar @$self]} elements.\n";
> }

would your design be helped if you thought about those bits before
and after the $self->_report() as functional entities that could be
implemented as _header() and _footer()? Then you could make your base
class something like (leaving the new() and gen() methods out:

sub Report::report()
{
    my $self = shift;
    $self->_header();
    $self->_report();
    $self->_footer();
}
sub Report::_header { return }
sub Report::_footer { return }
sub Report::_report { croak "_report must be implemented" }

And the Extended:

@ExtendedReport::ISA = qw( Report );
sub ExtendedReport::_header { print "We will count elements\n" }
sub ExtendedReport::_footer { my $e = @{$_[0]}; print "$e elements\n" }

And the others:

@OddReport::ISA = qw( ExtendedReport );
sub OddReport::_report { print "Odd report here\n" }

@EvenReport::ISA = qw( ExtendedReport );
sub EvenReport::_report { print "Even report here\n" }

and keep the inheritance tree the same. If you now later decide you want
different headers, you change the inheritance of the child classes, and
presto. Or if you don't want headers and footers anymore, you go back to
inheriting from Report directly. And all the required functionality is
proscribed from the base class up, not the other way around.

> Both solutions are not good OO.  Ideally, when I insert a middle layer,
> the only thing I have to do is re-directing the inheritance link @ISA.

OO doesn't say much about renaming or reworking classes and inheritance.
It talks about how classes should be designed and such, but not about
how you go about when you re-organise things. it is concerned with the
end result only.

> How would you solve this problem?

By redesigning the whole thing, and then changing the classes according
to the new design.

> No matter the OddReport ISA Report or ISA Extended report, its method should
> always be "sub report" instead of "report" today and "_report" tomorrow.

Then maybe you should consider using the last method I suggested, with
the header and footer stuff.

Martien
-- 
Martien Verbruggen              | 
Interactive Media Division      | System Administration is a dirty job,
Commercial Dynamics Pty. Ltd.   | but someone said I had to do it.
NSW, Australia                  | 


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

Date: 17 Aug 2001 17:50:05 -0500
From: Ren Maddox <ren@tivoli.com>
Subject: Re: Perl OO needs the opposite of SUPER::
Message-Id: <m31yma1eua.fsf@dhcp9-161.support.tivoli.com>

On 17 Aug 2001, johnlin@chttl.com.tw wrote:

> Let me show the problem I encountered in real case.  (Simplified, of
> course.)

OK.  I've taken your example and changed it to use what I consider the
more normal solution.  The trick is to separate the part that you want
the intermediate class(es) to override from the part that you want the
final class(es) to override.

I won't post both versions, but it should be pretty clear that the
only change required when adding ExtendedReport is to change the @ISA
for the subclass(es).  In this case, I've changed EvenReport's but not
OddReport's to help demonstrate that no other changes are required.


#!/usr/bin/perl
use strict;
use warnings;

package Report;

sub new {  # $self->new(1,5,2,6,4);    input a list of numbers
    my $self = shift;
    bless \@_,ref($self)||$self;
}

sub pre_report {
    my $self = shift;
    print "Now generating report for ",ref($self),"(@$self)\n";
}

sub post_report {
    print "Done, hope you will like it.\n";
}

sub gen {
    my $self = shift;
    $self->pre_report(@_);
    $self->report(@_);    
    $self->post_report(@_);
}                          

sub report {return}   # please inherit and override


package ExtendedReport;
our @ISA = qw/Report/;

sub pre_report {
    my $self = shift;
    $self->SUPER::pre_report(@_);
    print "NOTE: every report will add element counting.\n";
}

sub post_report {
    my $self = shift;
    print "There are @{[scalar @$self]} elements.\n";
    $self->SUPER::post_report(@_);
}


package EvenReport;
our @ISA = qw/ExtendedReport/;

sub report {
    my $self = shift;
    my $count = grep {$_%2 == 0} @$self;
    print "There are $count even numbers.\n";
}


package OddReport;
our @ISA = qw/Report/;

sub report {
    my $self = shift;
    my $count = grep {$_%2} @$self;
    print "There are $count odd numbers.\n";
}

package main;
EvenReport->new(1,5,2,6,4)->gen;
OddReport->new(5,6,1,4,2)->gen;

__END__

-- 
Ren Maddox
ren@tivoli.com


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

Date: Fri, 17 Aug 2001 23:54:45 GMT
From: Bart Lateur <bart.lateur@skynet.be>
Subject: Re: Processing a scalar in the same way of a filehandle
Message-Id: <vfbrnt89d09pcdl7efenap68l6vl67i9uo@4ax.com>

Anno Siegel wrote:

>> My version came from CPAN this afternoon. It can't be moving THAT
>> fast... Uh... version is 1.126?!? What is going on?!?
>
>Got my 2.104 from ftp://ftp.uni-hamburg.de/pub/soft/lang/perl/CPAN/
>also this afternoon (and with a .be account your afternoon would be
>my afternoon).

Well... I got it from IO-stringy-1.220 (note the lower case "s").

 ...

I figured out what's going on. Apparently, the first release of
IO::Stringy 2.x is only 10 days old. I had an old copy of
"02packages.details.txt" (see
<http://www.cpan.org/modules/02packages.details.txt.gz>), so it was the
previous version on the module that got installed with me.

BTW I'm using IndigoPerl. I must check out why I didn't get an updated
copy of that file by itself. I had to throw the old file away, and then,
of course, I got an new copy.

-- 
	Bart.


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

Date: Sat, 18 Aug 2001 00:12:39 GMT
From: Bart Lateur <bart.lateur@skynet.be>
Subject: Re: Processing a scalar in the same way of a filehandle
Message-Id: <hqcrntcq7gc78l08oo92s5mhs61fihgpcd@4ax.com>

John Porter wrote:

> for my $p ( split /\n+/, $cnt ) { ... }

Paragraph mode demands  a separation of at least 2 newlines.

	for my $p ( split /\n\n+/, $cnt ) { ... }

-- 
	Bart.


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

Date: 17 Aug 2001 23:13:01 GMT
From: Tarak Parekh <tarak@lectura.CS.Arizona.EDU>
Subject: redirecting stdin and stdout
Message-Id: <9lk8dt$q9j$1@hisatsinom.cs.arizona.edu>

Hello, 

I have a small perl script that basically invokes the 'system'
function call.
Before invoking the system function call I try redirecting the
STDERR and STDOUT to a file handle by doing

*STDOUT=*FILE_HDL;
*STDERR=*FILE_HDL;

After that i invoke
system ("/tmp/a.out");

Anything that a.out prints does not get redirected to the file_hdl
but whatever I print in the script does get redirected. I am guessing
that the stdout and stderr file descriptors are unchanged in the 
binary that I am trying to execute in the system function call. Is that
true ? Or am i missing something.

What would be the right way to redirect standard out and standard error
messages from a binary invoked by the system function call ?

thanks a lot, 
-- tarak


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

Date: Sat, 18 Aug 2001 00:21:34 GMT
From: Bart Lateur <bart.lateur@skynet.be>
Subject: Re: regexp question with no answer yet
Message-Id: <62drntoasm8idhoell36iagrndp5sefb32@4ax.com>

Anno Siegel wrote:

>Parse the regex (Parse::RecDescent should do that easily)

Perhaps YAPE::Regex, or one of its brethren, would be a more natural
choice...?

Has anybody actually used this module for anything, yet?

-- 
	Bart.


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

Date: Sat, 18 Aug 2001 00:22:30 GMT
From: john smith <nospam@newsranger.com>
Subject: removing trailing and leading blanks
Message-Id: <azif7.5616$2u.53976@www.newsranger.com>

What is the most efficient way of removing leading and trailing
blanks from a string.

for e.g., "john smith     " should become "john smith"

and "   john smith" should become "john smith".
Is there a standard perl function for either of this.




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

Date: Fri, 17 Aug 2001 22:11:55 GMT
From: "John W. Krahn" <krahnj@acm.org>
Subject: Re: Searching Text File
Message-Id: <3B7D9704.F7AA8F63@acm.org>

tazjrg2 wrote:
> 
> I am trying to search a Text File using PERL.
> 
> The text file is a common Compaq File called SURVEY.TXT.  It has a
> setup like this:
> 
> ========================
> Operating System ....................(+) Microsoft Windows NT Server
> 4.0
>                                          (build 1381)  Service Pack 6
>                                      (-) Microsoft Windows NT Server
> 4.0
>                                          (build 1381)  Service Pack 1
>  EISA Configured Primary OS ............ Windows NT 4.0
> ========================
> 
>  I currently have a subroutine that works great, but is limited.  The
> current code:
> ========================
> @startstring = ("Operating System");
> @startlength = (41);
> @stoplength = (36);

No need for a stop length as substr() will do the right thing.

> $long = @startstring;

No need for $long just use an array in scalar context.


my @lookup = ( [ 'Operating System', 41 ],
               [ 'Something Else',   32 ],
               [ 'etc...',           5  ],
               );


> sub chkfile {
>         print OUTFILE "$srvrname;";

You shouldn't use global variables unless the program is really small.


>         $srvrfile =  "\\\\$srvrname\\c$\\compaq\\survey\\survey.txt";
>         open( fileinput1, "$srvrfile" ) || warn "Unable to open input
> file $srvrfile";

Here you are trying to open a file and _even if it fails_ you continue
as if it had succeeded.

       unless ( open fileinput1, $srvrfile ) {
             warn "Unable to open input file $srvrfile: $!";
             return;
             }

>                 @infile = ( <fileinput1> );
>         close( fileinput1 );
>         for ($loop = 0; $loop < $long; $loop++) {
>                 $flag = "init";
>                 foreach $line (@infile) {
>                         if ($line =~ /^$startstring[$loop]/) {
>                                 $flag = "begin";
>                                 }
>                         if ($flag eq "init") {
>                                 next;
>                                 }
>                         if ($flag eq "end") {
>                                 next;
>                                 }
>                         elsif ($flag eq "begin") {
>                                 $getvalue = substr($line,
> $startlength[$loop], $stoplength[$loop]);
>                                 chomp($getvalue);
>                                 print OUTFILE "$getvalue;";
>                                 $flag = "init";
>                                 next;
>                                 }
>                         }
>                 }

        while ( <fileinput1> ) {
            for my $ref ( @lookup ) {
                if ( /^$ref->[0]/ ) {
                    chomp( my $getvalue = substr( <fileinput1>,
$ref->[1] ) );
                    chomp( $getvalue .= substr( <fileinput1>, $ref->[1]
) );
                    print OUTFILE "$getvalue;";
                    }
                }
            }


>         print OUTFILE "\n";
>         }
> ==========================
> 
> The problem is, what this returns to me is "Microsoft Windows NT
> Server 4.0 " - IT DOES NOT READ the next lines of the file.
> 
> Does anyone know how I could modify this so that it would take all of
> the information, "Microsoft Windows NT Server 4.0  (build 1381)
> Service Pack 6"??



John
-- 
use Perl;
program
fulfillment


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

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


Administrivia:

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

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

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 V10 Issue 1555
***************************************


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