[9706] in Perl-Users-Digest

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

Resend: Perl-Users Digest, Issue: 3299 Volume: 8

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sat Aug 1 19:27:16 1998

Date: Sat, 1 Aug 98 16:19:04 -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           Sat, 1 Aug 1998     Volume: 8 Number: 3299

Today's topics:
        How do I attach a Global Variables File to each of my s (Scott Cherkofsky)
    Re: How do I attach a Global Variables File to each of  <jdporter@min.net>
    Re: How do I attach a Global Variables File to each of  <quednauf@nortel.co.uk>
    Re: How do I attach a Global Variables File to each of  (Tad McClellan)
    Re: How to change one field in a flat database? (I.J. Garlick)
    Re: How to change one field in a flat database? thomastk@hotmail.com
    Re: How to delete files inside perl script? <karseras@nortel.ca>
    Re: How to extrat characters from string <stepherd@gusun.georgetown.edu>
    Re: How to read a variable from another Perl program? (Steve Linberg)
        HTTP agent & framed pages <dbritton@worldnet.att.net>
        http and perl estokien@my-dejanews.com
    Re: http and perl (brian d foy)
    Re: http and perl <jdporter@min.net>
    Re: http and perl <joneil@cks.ssd.k12.wa.us>
    Re: I want to separate my Perl from my HTML <khaines@oshconsulting.com>
    Re: Inheritance broken when objects share a file? (Kevin Reid)
        Input text strings from two separate files into a singl tariqahsan@lucent.com
    Re: Input text strings from two separate files into a s <jdporter@min.net>
        Special: Digest Administrivia (Last modified: 12 Mar 98 (Perl-Users-Digest Admin)

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

Date: 31 Jul 1998 10:29:22 -0400
From: crusader@bobo.shirenet.com (Scott Cherkofsky)
Subject: How do I attach a Global Variables File to each of my scripts?
Message-Id: <6pskc2$lfc@bobo.shirenet.com>


I have a list of variables and constants that are used in each of a group of
scripts.  Right now I type each out at the beginning of each of my scripts and
if I have to make a change, it impacts all of my scripts.  What I would like
to do is link to a variable/constants file at the top of my scipts so I can
change the values once and have it propogate through to all of my scripts.

I've been looking into making a module for this but can't get my head around
the idea.

Whats the best / easiest way to do this?

Scott
-- 
____________________________________________________________________________
  Scott   |   scottc1033 aol com  | Need Interenet access in Virginia?
Cherkofsky|crusader shirenet com  |  Try Shirenet <mailto:info@shirenet.com>
'Crusader'|HomePage:    http://www.shirenet.com/~crusader/html/Home.html


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

Date: Fri, 31 Jul 1998 15:24:20 GMT
From: John Porter <jdporter@min.net>
Subject: Re: How do I attach a Global Variables File to each of my scripts?
Message-Id: <35C1E23D.22CA@min.net>

Scott Cherkofsky wrote:
> 
> I have a list of variables and constants that are used in each of a group of
> scripts.  Right now I type each out at the beginning of each of my scripts and
> if I have to make a change, it impacts all of my scripts.  What I would like
> to do is link to a variable/constants file at the top of my scipts so I can
> change the values once and have it propogate through to all of my scripts.

require.

put all the assignment statements in a file, say MyGlobals.pl; and the
line

	1;

at the end of that file; then in your programs, you put the line

	require "MyGlobals.pl";

If the directory where you put MyGlobals.pl is not in your @INC path
(yet),
you can add it; if, for example, it's in the current directory:

	use lib ('.');

-- 
John Porter


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

Date: Fri, 31 Jul 1998 16:02:48 +0100
From: "F.Quednau" <quednauf@nortel.co.uk>
Subject: Re: How do I attach a Global Variables File to each of my scripts?
Message-Id: <35C1DC98.F9FCA2EB@nortel.co.uk>

Scott Cherkofsky wrote:
> 

> 
> Whats the best / easiest way to do this?

One of many,many ways would be the following:

open CONFIG, "< /u/quednauf/temp/testfile.txt" or die "Vars could not be
set: $!";
while (<CONFIG>) { eval or print "$@"; }
close CONFIG;

print $new;

testfile.txt contained the following:

broken = 'Jammed';
$new = 'Crank';

The output was the following:

Can't modify constant item in scalar assignment at (eval 1) line 1, near
"'Jammed';"

Crank

-- 
____________________________________________________________
Frank Quednau               
http://www.surrey.ac.uk/~me51fq
________________________________________________


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

Date: Fri, 31 Jul 1998 10:01:00 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: How do I attach a Global Variables File to each of my scripts?
Message-Id: <c7msp6.pnd.ln@localhost>

Scott Cherkofsky (crusader@bobo.shirenet.com) wrote:

: I have a list of variables and constants that are used in each of a group of
: scripts.  Right now I type each out at the beginning of each of my scripts and
: if I have to make a change, it impacts all of my scripts.  What I would like
: to do is link to a variable/constants file at the top of my scipts so I can
: change the values once and have it propogate through to all of my scripts.

: I've been looking into making a module for this but can't get my head around
: the idea.

: Whats the best / easiest way to do this?


   perldoc -f require


--
    Tad McClellan                          SGML Consulting
    tadmc@metronet.com                     Perl programming
    Fort Worth, Texas


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

Date: Fri, 31 Jul 1998 08:12:07 GMT
From: ijg@csc.liv.ac.uk (I.J. Garlick)
Subject: Re: How to change one field in a flat database?
Message-Id: <Ewy9G7.GAw@csc.liv.ac.uk>

In article <35c08f18.6348164@news.algonet.se>,
news@NOSPAM.gb-design.com (Bjorn Malmberg) writes:
> Hi folks!
> 
> I have a problem here. I have a flat database with about 70 lines and
> about 350 fields that looks like this:
> 
> Bjvrn Malmberg&&aaaaa@aaaaa.com&&111-111 111&&222-222 222&&1111
> 
> Where the first field is name, the second email, third phone number,
> fourth cellular, and last a password...
> 
> I want to search and replace the email field after checking that the
> password is correct. I've come so far that it checks for the right
> password, but I can't get it to change the email as it's supposed
> to....

The following might work:

	#- first
	open (FH, $oldfile) || die "Can't open $oldfile: $!";
	open (NFH, ">$newfile") || die "Can't open $newfile: $!";
	while (<FH>) {
	#- end first
		if (/^$ckname/ && /$ckpassword$/) {
			($name,$email,$the_rest) = split '&&', $_, 3;

			print NFH $name.'&&'.$new_email.'&&'.$the_rest;
		}
		else { print NFH; }
	#- second
	}
	close NFH;
	close FH;

	# now move temp new file to the old file name
	rename $new_file, $oldfile;
	#- end second

A far more rigorous example of the bits between the 'first' and 'second'
commented bits is available form perlfaq5
	"How do I change one line in a file/delete a line in a file/insert a line
	in the middle of a file/append to the beginning of a file?"
by Tom Christiansen and Nathan Torkington, but then you recon you can do
that bit?

Also I would find a copy of the camel and learn 'split' and 'join' as they
are probably two of the most useful builtin functions available in this
situation. (or perlfunc man page if you haven't got access to a copy of the
camel book)

> 
> I've been struggling around with this for a lot of time now, and I
> have no clue of what I can do... Can someone please help me?
> 
> TIA
> 
> Bj0rN

-- 
--
Ian J. Garlick
ijg@csc.liv.ac.uk

New systems generate new problems.


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

Date: Sat, 01 Aug 1998 09:09:32 GMT
From: thomastk@hotmail.com
Subject: Re: How to change one field in a flat database?
Message-Id: <6pum0b$9vo$1@nnrp1.dejanews.com>

In article <35c08f18.6348164@news.algonet.se>,
  news@NOSPAM.gb-design.com (Bjorn Malmberg) wrote:
> Hi folks!
>
> I have a problem here. I have a flat database with about 70 lines and
> about 350 fields that looks like this:
>
> Bjvrn Malmberg&&aaaaa@aaaaa.com&&111-111 111&&222-222 222&&1111
>
> Where the first field is name, the second email, third phone number,
> fourth cellular, and last a password...
>
> I want to search and replace the email field after checking that the
> password is correct. I've come so far that it checks for the right
> password, but I can't get it to change the email as it's supposed
> to....
>

I normally do this by writing the updated record to a new temporary datafile
along with the old records, and then renaming back to its actual name.

Cheers, Thomas.

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum


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

Date: Fri, 31 Jul 1998 16:38:53 +0100
From: Andreas Karseras <karseras@nortel.ca>
Subject: Re: How to delete files inside perl script?
Message-Id: <35C1E50D.32DA@nortel.ca>

Maybe try checking your permissions?

AK

Calle Dybedahl wrote:
> 
> Meena Chockalingam <cmeena@hotmail.com> writes:
> 
> > I used unlink and it does not work either.
> 
> Have you tried turning the computer on?
> 
> (Free clue: "doesn't work" is somewhat vague)
> --
>                     Calle Dybedahl, UNIX Sysadmin
>        qdtcall@esavionics.se  http://www.lysator.liu.se/~calle/


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

Date: Thu, 30 Jul 1998 09:42:57 -0400
From: Dave Stephens <stepherd@gusun.georgetown.edu>
To: Juan Guevara <chapin@ecst.csuchico.edu>
Subject: Re: How to extrat characters from string
Message-Id: <35C07861.73F78B0C@gusun.georgetown.edu>

Sure, use substr,

syntax:  substr ($string, skipchars, length)

example:

$string = "Now is the time for all";
$sub = substr ($string, 11, 4);
print "$sub";

output of this would be:
    time

If you leave out the length feature you will get the rest of the
string, so if you were to omit the "4" in the above example
the output would be:
    time for all

--Dave Stephens




Juan Guevara wrote:

> Hello,
>
> How do you get a character from a string, specifying
> the index where it is located.  For example, if I say:
>
> $index=index $string,$findthis;
>
> Is there a function that does the following:
> $char = get_me_character_at_$index($string);
>
> thanks, -juan
> --
> Juan Guevara
> chapin@ecst.csuchico.edu        *Make every move as if it were your last*
> http://www.ecst.csuchico.edu/~chapin





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

Date: Thu, 30 Jul 1998 16:04:37 -0400
From: linberg@literacy.upenn.edu (Steve Linberg)
Subject: Re: How to read a variable from another Perl program?
Message-Id: <linberg-3007981604370001@projdirc.literacy.upenn.edu>

In article <6pqcru$g50$1@nnrp1.dejanews.com>, guna@my-dejanews.com wrote:

> Hi,
>    i have two independant perl programs, say "server" and "client".
> The "server" starts something like,
> 
> #!/usr/local/bin/perl
> 
> $myname = "John Steamer";
> .
> .
> 
> Now, is there a way i can read $myname from "client" without actually parsing?
> something like an "extern" in "C" programs. If i use "require" it actually
> executes the "server" code which i don't want.

Take your pick:

Put it in a text file/database/etc.
Set an environment variable.
Pass it as a parameter.
Merge your programs.
_____________________________________________________________________
Steve Linberg                       National Center on Adult Literacy
Systems Programmer &c.                     University of Pennsylvania
linberg@literacy.upenn.edu              http://www.literacyonline.org


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

Date: 31 Jul 1998 16:28:23 GMT
From: "Donald Britton" <dbritton@worldnet.att.net>
Subject: HTTP agent & framed pages
Message-Id: <6psrb7$rs9@bgtnsc02.worldnet.att.net>

Greetings,

I'm not sure if this is the correct forum, but I don't know where else to
turn.

I have developed a small script to download web pages automatically and
store them for subsequent parsing. It works great and is surprisingly easy
to do in perl.  However, whenever I try to access a web site which uses
framed pages, I get the response that my browser is not frames-enabled.  How
does the server know which browser I'm using?  I thought this was derived
from the User-Agent field passed with the GET HTTP command.  Here's some of
my code:

    $doc_name =  "/" . $doc_name;
    $request = "GET $doc_name HTTP/1.0\r\n";
    $request .= "From: dbritton@worldnet.att.net\r\n";
    $request .= "User-Agent: Mozilla/4.0 (compatible; MSIE 4.0; Windows
95)\r\n";
    $request .= "Accept: text/plain, text/html\r\n";
    $request .= "\r\n";
    print(sock $request);

Unfortunately, this doesn't seem to work.  I tested this with a little cgi
program and the server is receiving these fields correctly.  Does anyone
know why this code can't grab framed web pages?  Is it the Accept field?  I
don't recall seeing other values that would do the job either.

(I realize that since this is really a type of web agent, I should actually
provide a unique name for the agent, but that doesn't seem to work either.)

Thanks for taking the time to read this and thanks for any help you can
provide.

Don Britton
dbritton@worldnet.att.net





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

Date: Fri, 31 Jul 1998 20:40:17 GMT
From: estokien@my-dejanews.com
Subject: http and perl
Message-Id: <6pta3h$fp3$1@nnrp1.dejanews.com>

I have a question for those who may be knowledgable in such things.  I am
attempting to write a script that will provide a web interface for an
application.  There is going to be an area in which the program will need to
check information inputted by the user by using a cgi-script on a business
partner's server.  It seems like a doable task, but how would I get perl to
call a program through http, get the output of the program and process it. 
Are there modules for this?  Or is there a simple function call that I can
use?  Any ideas or advice?

-Eric Stokien
support@ttone.com

replies by e-mail would be best for me, but I will attempt to see if anyone
answers on this newsgroup.

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum


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

Date: Fri, 31 Jul 1998 17:10:14 -0500
From: comdog@computerdog.com (brian d foy)
Subject: Re: http and perl
Message-Id: <comdog-3107981710140001@news.panix.com>
Keywords: just another new york perl hacker

In article <6pta3h$fp3$1@nnrp1.dejanews.com>, estokien@my-dejanews.com posted:

> I have a question for those who may be knowledgable in such things.  I am
> attempting to write a script that will provide a web interface for an
> application.

see the LWP module.

good luck :)

-- 
brian d foy                                 <http://computerdog.com>
Comprehensive Perl Archive Network (CPAN) <URL:http://www.perl.com>
Perl Mongers <URL:http://www.pm.org>


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

Date: Fri, 31 Jul 1998 21:25:09 GMT
From: John Porter <jdporter@min.net>
Subject: Re: http and perl
Message-Id: <35C236CD.3645@min.net>

estokien@my-dejanews.com wrote:
> 
> how would I get perl to call a program through http,
> get the output of the program and process it?
> Are there modules for this?  

But of course.  LWP::UserAgent gives a simple web client
interface; and if you need to parse the HTML you get back,
you can use HTML::Parse.  For writing CGI programs, you
should use the CGI module; you can even make your
program be its own HTTP server, rather than have to
go through some other process (like httpd), by using the
CGI::MiniSvr module.

In general, the first thing to do is check on CPAN to see
if there are any modules that do what you need.
The overview, including brief descriptions of the most 
useful modules, is at
	http://www.perl.com/CPAN/CPAN.html

-- 
John Porter


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

Date: Fri, 31 Jul 1998 15:17:38 -0700
From: Jerome O'Neil <joneil@cks.ssd.k12.wa.us>
To: estokien@my-dejanews.com
Subject: Re: http and perl
Message-Id: <35C24282.86940B09@cks.ssd.k12.wa.us>

estokien@my-dejanews.com wrote:
> 
> I have a question for those who may be knowledgable in such things.  I am
> attempting to write a script that will provide a web interface for an
> application.  There is going to be an area in which the program will need to
> check information inputted by the user by using a cgi-script on a business
> partner's server.  It seems like a doable task, but how would I get perl to
> call a program through http, get the output of the program and process it.
> Are there modules for this?  Or is there a simple function call that I can
> use?  Any ideas or advice?

Use LWP within your CGI to call the remote CGI and return the values.  I
do this with one of my applications, and it works well.  I use the HEAD
method and assigne the results to a hash for easy access.

Good Luck!

Jerome


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

Date: Thu, 30 Jul 1998 08:07:00 -0600
From: "Kirk D. Haines" <khaines@oshconsulting.com>
Subject: Re: I want to separate my Perl from my HTML
Message-Id: <6ppuec$q3k$1@news-1.news.gte.net>

[reply via both email and clpm]
pjgeer@my-dejanews.com wrote:
> 
> I write CGIs that output HTML.  I want to separate the HTML from the Perl so I
> can edit (or have someone else edit) just the HTML by itself, without worrying
> about busting the script.  I had been using here docs to handle blocks of HTML
> but I get mad about things like the code below.  How can I separate the HTML
> from the Perl?:
> print <<"EOF";
> ...
> <SELECT Name="languages">
> EOF
> foreach $record ( @records ) {
>   print "<OPTION Value=\"$record.txt\">$record</OPTION>\n";
> }
> print <<"EOF";
> </SELECT>
> EOF

Read it from a file, using some sort of template mechanism for the
programatically generated portions of the content.

At the simple end of the spectrum, this can be implimented simply by
placing markup tags within your HTML file for simple tasks.

For example:

content.html
---
<html>
<head>
<title><!--TITLE--></title>
</head>
<body>
<p>The date is <!--DATE-->
<p>Below is a list of all the environment variables.
<!--ENV-->
</body>
</html>
---

index.cgi
---
#!/usr/bin/perl
use CGI;
use POSIX qw();

my $cgi = new CGI();
print $cgi->header();
open(HTML,"<content.html");
while (<HTML>)
{
    s/<!--TITLE-->/$cgi->param('title') ? $cgi->param('title') : 'No
Title'/eg;
    s/<!--DATE-->/{POSIX::strftime('%m-%d-%Y
%H:%M:%S',localtime(time()));}/eg;
    s/<!--ENV-->/{my $r;
                  $r .= "<ul>\n";
                  foreach $t (sort(keys(%ENV))) {$r .= "<li>$t --
$ENV{$t}\n";}
                  $r .= "<\/ul>";
                  $r}/ex;
    print;
}
close(HTML);
---

The output of this would be something like:

The date is 07-29-1998 13:02:28 

Below is a list of all the environment variables. 

    DOCUMENT_ROOT -- /home/httpd/html 
    GATEWAY_INTERFACE -- CGI/1.1 
    HTTP_ACCEPT -- image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
image/png, */* 
    HTTP_ACCEPT_CHARSET -- iso-8859-1,*,utf-8 
    HTTP_ACCEPT_LANGUAGE -- en 
    HTTP_CONNECTION -- Keep-Alive 
    HTTP_HOST -- localhost 
    HTTP_PRAGMA -- no-cache 
    HTTP_USER_AGENT -- Mozilla/4.04 [en] (X11; I; Linux 2.0.33 i586) 
    PATH -- /sbin:/usr/sbin:/bin:/usr/bin 
    QUERY_STRING -- 
    REMOTE_ADDR -- 127.0.0.1 
    REMOTE_HOST -- localhost 
    REMOTE_PORT -- 10597 
    REQUEST_METHOD -- GET 
    REQUEST_URI -- /index.cgi 
    SCRIPT_FILENAME -- /home/httpd/html/index.cgi 
    SCRIPT_NAME -- /index.cgi 
    SERVER_ADMIN -- root@localhost 
    SERVER_NAME -- foo.bar.com 
    SERVER_PORT -- 80 
    SERVER_PROTOCOL -- HTTP/1.0 
    SERVER_SOFTWARE -- Apache/1.3b5

If your needs are more sophisticated, a more sophisticated template
system would be called for.  Text::Template and Data::Locations on CPAN
may both offer something to you in this area.  I also have a module
which I am tentatively calling Data::Template which I wrote to meet a
need for templates that I didn't see being met yet.  The first draft of
the man page for this module is at the end of this email.  Let me know
if you are interested in using it as it currently is not available
except by request to me.


Kirk Haines


Data::Template manpage (cut -n- paste from pod2html output)
---
Data::Template 

Data::Template - Perl extension to impliment a simple, fast, reusable
template that can consist of static content as well
as arbitrary dynamic text returned by arbitrary callback functions. 



SYNOPSIS 

  use Data::Template;
  
  $template = new Data::Template();

  $template->addRule(regex => '\b((?i)t\w*)',
                     callback => \&upc,
                     parameters => '$1',
                     cache => 'p2');
  $template->addRule('\b((?i)t\w*)',\&upc,'$1','p2');

  $template->deleteRule(regex => '\b((?i)t\w*)');
  $template->deleteRule('\b((?i)t\w*)');

  $rule = $template->getRule(regex => '\b((?i)t\w*)');
  $rule = $template->getRule('\b((?i)t\w*)');

  $template->setText(text => 'This is some text to <!--WORD-->
<!--PHRASE-->');
  $template->setText('This is some text to <!--WORD--> <!--PHRASE-->');

  $text = $template->getText();

  $template->parse();

  $template->process(ARG1,ARG2,ARG3,...,ARGn);

  $template->dump();

  $template->info();



DESCRIPTION 

Data::Template is designed to be a efficient, flexible, and moderately
easy to use module for reusable templates
composed of static text data interspersed with dynamically defined text
returned from callback routines. It's best use is
probably in an application where a single template may be referenced
multiple times during the course of the
application's lifespan. 

Data::Template requires both text and a list of rules to apply to that
text in order to produce the internal template
structure. The text is passed as a simple scalar value to the setText()
method. 

Rules are actually regular expressions which are applied to the text of
the template. The other parts of a rule definition
is a callback function to invoke upon a successful match of the rule's
regex, a list of parameters -- typically
backreferences to the rule's regex -- to pass to the callback, and an
optional caching specification that defines how
Data::Template is to cache return values from the callback. 



CACHING 

The default mode of operation for a callback is to not cache any of the
return values. For functions which will return a
consistent value based on a consistent set of parameter input, however,
calling it multiple times is likely very
inefficient. 

An example would be a program to display a user's profile information
for some web based application or service.
Some things on this web page will be static. That is, some portions of
the web page will be the same for everyone who
sees the page and will not change. However, interspersed throughout the
page will also be content which is applicable
only to one user's specific session. In addition to their own private
settings, there may be some things such as the
current date and time or the latest system updates that will vary by
user and by session, and there may be some things
such as the start time for some process invoked by this application
which, though not static, will not change once
established. If the program that produces these web pages is persistent,
such as programs running under mod_perl or
fastCGI, and if the program is using Data::Template, caching could be
quite useful for certain portions of the page. 

For information which, though dynamic in nature, does not vary once
established, it makes little sense to actively
invoke a method every time this information is needed. Data::Template's
notion of permanent caching is intended for
this kind of data. Permanent caching is implied by setting the cache
value of a rule to 'p'. When a callback with
permanent caching is called, Data::Template remembers what parameters
were passed to the callback. If that same
callback is invoked again later with the same set of parameters, the
value returned by the first invocation of that
callback with those parameters is pulled from a hash and immediately
returned, thus avoiding the expense of calling a
routine that we already know the return value of. This type of caching
is great for content that is constant for the entire
lifetime of a program. However, what happens if content is only valid
for a limited time? 

Data::Template provides a second type of caching. This caching, called
interval caching, only provides caching for
that period of time that a given call to process() is operating. As an
example, consider a tag, <!--TIME--> in a
document being prepared through Data::Template. <!--TIME--> returns the
current data and time in a specific
format, and should return the exact same date and time for all
occurences of the tag in the document for any one given
processing of that document. 

If there were only one reference to <!--TIME--> in the document, there
would be no reason to bother caching it. After
all, the cached value will never be used. If, however, <!--TIME-->
appears 12 times in the document, there may be a
significant savings by caching the result. To specify interval caching,
set the cache value of a rule to 'i'. Then, the first
time in any given call of process() that the callback is invoked, it
will go ahead and calculate its return value
normally. Thereafter, invocations with the same parameters that occur in
the same run through the process()
method will simply return the cached value from the first invocation out
of the cache hash. 

There are also times when no caching is desired, ever. If a callback is
always going to return a different value, or if you
know that a callback may be invoked many times, but will always be
invoked with a different set of parameters,
caching makes no sense. To avoid caching, set the cache value of the
rule to 'n'. 

It'd be great if the caching mechanism could be sufficiently versatile
as it is described above. However, it has some
problems. What if one were passing into the process() call an object
which represents a user of your application. The
application will, in its lifetime, operate on many users. In a
Data::Template object is defined a rule with permanent
caching enabled. Without more control on how caching is performed for a
given callback, permanent caching likely
would not work correctly in a situation like this. If each user passed
to the process() call were a unique object, the
return value for a call to a permanently cached callback would be cached
under a unique ID every time a call is made
into process() with a new user. 

The solution to this problem is to add a second specification to the
caching description which defines which parameter
set(s) to use when generating the ID for the caching of the return value
of a callback. 

This second specification is a single digit that maps as follows: 0
Cache based only on the callback and not on either
parameter set 1 Cache based only on the parameters passed via process()
2 Cache based only on the parameters
groked from the rule's regex 3 Cache based on both sets of parameters 

Thus, a complete caching specification consists of two characters, an
alphabetic character and a numeric character. i.e.
``p0'' ``i2'' 

The default behavior, should no alphabetic character be provided, is no
caching for the callback. Likewise, the default
behavior should no numeric character be provided (or an invalid -- > 3)
is to default to using both sets of parameters
for caching. 



METHODS 

new() 

new() does not accept any parameters. It returns a new object of type
Data::Template with all values initialized to null
or zero. 

addRule(regex => '(text)', callback => &\myFunction, parameters => '$1',
cache => 'p2'); 

When called, inserts the rule defined in the call to the rulelist for
the template. The regex parameter takes any valid
regular expression. The callback function is invoked if the regexp
evaluates to true. Backreferences are typically used
to create parameters to pass to the callback function. callback takes a
reference to a function. For simple actions,
anonymous functions can be useful here. Data::Template will
automatically take care of caching the function. The
callback function will receive two parameters. The first is an array
reference containing the parameters groked from
the regex and the parameters values in the rule that triggered the
callback. The second is a reference to an array
containing whatever parameters were passed in when process() was
invoked. The return values of the callback is
substituted in place of the text that the regex matched. addRule returns
the current number of defined rules. 

deleteRule(regex => '(test)') 

This function deletes the rule, if any, that has a regex value which
matches the value passed to the function. It returns
the number of defined rules. 

getRule() 

getRule(regex => '(text') 

If a regular expression is passed to getRule(), it returns a hash
containing the specification of the rule that matches.
If no regex is passed, an array containing all of the defined rules is
returned. See below for the structure of a rule hash. 

setText(text => 'This is some template text.'); 

The text of the template is provided through the use of this function.
The return value of the function is the text that
was passed in. 

getText() 

getText returns the text of the template in the Data::Template object. 

reset() 

This will reset the rulelist, informational statistics, and text of the
Data::Template object to their original 0, null, or
empty values. 

parse() 

Before Data::Template can be used, it must be parsed. Parsing is
performed by iterating over the text of the template
with the list of rules. The regex that matches closest to the start of
the text is applied by first placing all of the text
before the text that matched the regex and inserting it as a scalar
value into an internal document array. A 'location'
hash is created which contains the resolved parameter list, the callback
to invoke, the caching type to apply to the
callback, and a few other internal bits of information. This is then
pushed onto the document array. This process is
repeated until the entire template has been parsed and pushed onto the
document array either as scalar strings or as
location hashes. parse() returns the number of elements, both scalar
strings and location hashes, which were parsed
from the text of the template. 

process(ARG1,ARG2,...ARGn) 

After the template has been parsed, it can be actively used to produce
content. process() can be called with any
arguments that one desires to pass on to the callback functions. Each of
the location hashes are iterated through and
the callback functions are called in order to resolve each of those
locations into scalar text. 

dump() 

Returns a scalar containing the text of the template with all of the
results from the callbacks called during
process()ing included at the correct points. 

info() 

Returns an internal hash that contains some general information on the
Data::Template object, it's contents, and how it
has been used. 



DATA STRUCTURES 

LOCATION 
callback 
    function to call to generate content 

parameters 
    parameters to pass to callback 

cache 
    cache type specification 

content 
    scalar returned by last invocation of the callback 

last_process 
    an id to identify the last invocation of process() in order to
manage interval caching properly 

INFO 
addrule 
    the number of times addRule has been called 

deleterule 
    the number of times deleteRule has been called 

getRule 
    the number of times getRule has been called 

rulecount 
    the current number of defined rules 

gettext 
    the number of times getText has been called 

settext 
    the number of times setText has been called 

parse 
    the number of times parse has been called 

locations 
    the number of defined locations in the document (where a location is
content defined by a callback) 

elements 
    the number of discrete elements in the document 

process 
    the number of times process has been called 

dump 
    the number of times dump has been called 



EXAMPLES 



Trivial Example 

The code that follows illustrates creating a Data::Template object, and
then populating it with rules and doing
something with it. 

----- 

#!/usr/bin/perl 

use strict; use Data::Template; use POSIX qw(strftime); 

my ($template) = new Data::Template(); $template->setText(<<EOT); This
is some sample text. There really is
nothing interesting here. However, this was generated at: <!--TIME-->
EOT 

$template->addRule(regex => '\b((?i)t\w+)', callback => \&upc,
parameters => '$1', cache => 'p2');
$template->addRule(regex => '<!--TIME-->', callback => \&time_date,
parameters => '', cache => 'n0');
$template->parse(); $template->process(time()); my ($out) =
$template->dump(); print ``$out\n''; 

sub upc { my ($param,$proc_param) = @_; return uc(@{$param}[0]); } 

sub time_date { my ($param,$proc_param) = @_; my ($time) =
@{$proc_param}[0]; return
POSIX::strftime('%m/%d/%Y %H:%M:%S',localtime($time)); } 

----- 

After creating a new instance of Data::Template with a call to new(),
the raw text of the template is fed to our new
Data::Template object with setText(). Following this, two rules are fed
to the object. 

The first matches all words that start with a 't' case insensitively. It
passes as a parameter the word that was matched
and is permanently cached. 

The second rule matches '<!--TIME-->', but does not pass any parameters
to the callback. 

parse() is called to resolve the rules to locations. 

process() is called, passing the return value from time() as a
parameter. 

Then we assign call dump() to return the processed template. 

Here's what happens when it is executed: 

THIS is some sample TEXT. THERE really is nothing interesting here.
However, THIS was generated at: 07/20/1998
16:03:59 



AUTHOR 

Kirk Haines, khaines@oshconsulting.com


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

Date: Thu, 30 Jul 1998 15:45:59 -0400
From: kpreid@ibm.net (Kevin Reid)
Subject: Re: Inheritance broken when objects share a file?
Message-Id: <1dcwfal.1dkvgyz17wyda8N@slip166-72-108-190.ny.us.ibm.net>

Russ Allbery <rra@stanford.edu> wrote:

> Russ Allbery <rra@stanford.edu> writes:
> 
> > But if you do:
> 
> > windlord:~> perl -w
> > package B;
> > sub alloc { bless {}, $_[0] }
> > package D;
> > @ISA = qw(B);
> > sub new { $_[0]->alloc() }
> > package main;
> > D->new ();
> 
> > it runs fine.  So D::new() is not seeing B::alloc() when you're calling
> > D::new() from before B::alloc() is declared.
> 
> > I have to admit this isn't precisely the behavior I'd expect either,
> 
> Oh, wait.  I see what's wrong.  @ISA isn't getting set until runtime, of
> course, and therefore @ISA isn't set at the time of the call to D->new()
> if you put that call before the assignment to @ISA.
> 
> If you put @ISA in a BEGIN { } block, things will work as you expect.

For a neater solution, try this:

"ISA.pm":

package ISA;

sub import {
  shift;
  print "\@_ = @_, caller = @{[scalar caller]}\n";
  @{caller() . '::ISA'} = @_;
}

1;

__END__

#!perl -w

use ISA qw(Something);

print @ISA, "\n";

__END__

-- 
  Kevin Reid.      |         Macintosh.
   "I'm me."       |      Think different.


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

Date: Thu, 30 Jul 1998 15:32:04 GMT
From: tariqahsan@lucent.com
Subject: Input text strings from two separate files into a single file
Message-Id: <6pq3lk$3f2$1@nnrp1.dejanews.com>

Hi,

I have a newbie question. I have to create a text file that will contain two
columns of text string data. But each of these two columns has to get its
input data from two separate files. The first column contains file directory
path info and the second column is suppose to have its corresponding group
name. After the first column is inputted its corresponding group name has to
be searched from a data dictionary file and inserted into the second column
of the same row. Can someone give me a hint to solve these problem? Thanking
you in advance.

Tariq

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum


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

Date: Thu, 30 Jul 1998 16:12:23 GMT
From: John Porter <jdporter@min.net>
Subject: Re: Input text strings from two separate files into a single file
Message-Id: <35C09C08.2175@min.net>

tariqahsan@lucent.com wrote:
> 
> After the first column is inputted its corresponding group name has to
> be searched from a data dictionary file and inserted into the second column
> of the same row. Can someone give me a hint to solve these problem? 

Store the data dictionary in a hash variable.

Without seeing what the data look like, it's hard to give more specific
help.

-- 
John Porter


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

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


Administrivia:

Special notice: in a few days, the new group comp.lang.perl.moderated
should be formed. I would rather not support two different groups, and I
know of no other plans to create a digested moderated group. This leaves
me with two options: 1) keep on with this group 2) change to the
moderated one.

If you have opinions on this, send them to
perl-users-request@ruby.oce.orst.edu. 


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

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