[18310] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 478 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Mar 13 09:05:57 2001

Date: Tue, 13 Mar 2001 06:05:11 -0800 (PST)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Message-Id: <984492311-v10-i478@ruby.oce.orst.edu>
Content-Type: text

Perl-Users Digest           Tue, 13 Mar 2001     Volume: 10 Number: 478

Today's topics:
        [ANNOUNCE] XML::LibXSLT 0.94 <matt@sergeant.org>
    Re: Are global variables global per instance or per cla <michael-a-mayo@att.net>
    Re: Assigning string from between two patterns? (Tad McClellan)
    Re: Detecting User Country in CGI Script (Mihai N.)
    Re: Does a merge function exist? (Anno Siegel)
    Re: Exp. Perl/CGI programmer needed  (Tad McClellan)
        How to create c code from perl <jyyoung@hfx.andara.com>
        How to use result of grep as an array? (Chris Allen)
    Re: How to use result of grep as an array? (Anno Siegel)
        I need to graph some data  (cRYOFAN)
        method alias <thoren@southern-division.com>
    Re: method alias (Anno Siegel)
    Re: Millisecond Time Help (Yes I've consulted the FAQ) <npecca@yahoo.com>
    Re: Newbie SSI Time Format <a.peacock@chime.ucl.ac.uk>
    Re: perl2exe performance problem <clarke@hyperformix.com>
        puzzling do{} and map interaction <david.bouman@nl.xo.com>
    Re: puzzling do{} and map interaction (Anno Siegel)
    Re: RE Doubt (Tad McClellan)
    Re: reg exp question (Abigail)
        Search and replace several targets at once (was: Can a  nobull@mail.com
    Re: subroutine recursion? (Abigail)
    Re: subroutine recursion? <jonni@ifm.liu.se>
    Re: subroutine recursion? (Tad McClellan)
    Re: subroutine recursion? (Philip Lees)
    Re: subroutine recursion? <meisl@amvt.tu-graz.ac.at>
    Re: Tk based alarm clock <fellowsd@cs.man.ac.uk>
        Whoops! <nbr@newsbrowser.com>
        Digest Administrivia (Last modified: 16 Sep 99) (Perl-Users-Digest Admin)

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

Date: Tue, 13 Mar 2001 10:23:42 +0000
From: Matt Sergeant <matt@sergeant.org>
Subject: [ANNOUNCE] XML::LibXSLT 0.94
Message-Id: <tas99it5doja41@corp.supernews.com>

This is the first public release of XML::LibXSLT.

XML::LibXSLT is a Perl interface to the gnome libxslt module available at
http://www.xmlsoft.org/. It also comes with XML::LibXML, which is a minimal
interface to the libxml2 DOM library, though at this time no DOM methods are
supported - the module is merely a helper for XML::LibXSLT.

LibXSLT provides a very compliant, fast, XSLT engine for doing XML
transformations. I have tested it to be over twice as fast as the
XML::Sablotron library using the XSLTMark benchmark suite. Almost all
features of XSLT are supported in libxml, including keys() and xsl:import.
The underlying XML::LibXML also supports DTD validation and xinclude.

Available on the CPAN or at http://axkit.org/download/

-- 
<Matt/>

    /||    ** Founder and CTO  **  **   http://axkit.com/     **
   //||    **  AxKit.com Ltd   **  ** XML Application Serving **
  // ||    ** http://axkit.org **  ** XSLT, XPathScript, XSP  **
 // \\| // ** mod_perl news and resources: http://take23.org  **
     \\//
     //\\
    //  \\




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

Date: Tue, 13 Mar 2001 13:46:55 GMT
From: "Michael A Mayo" <michael-a-mayo@att.net>
Subject: Re: Are global variables global per instance or per class?
Message-Id: <jxpr6.6916$Rb.567370@bgtnsc05-news.ops.worldnet.att.net>

"Thomas" <webmuse@my-deja.com> wrote in message
news:8Zhr6.79$Y%3.35066@news1.mco...
> This question relates specifically to the PerlEx environment (and
> probably mod_perl), although the question itself is about how Perl
> handles global variables.

I don't know anything about PerlEx, but I can tell you about mod_perl.


> I am writing a fairly simple module that uses DBI, internally, to work
> with databases. I have set $SIG{__WARN__} to a error handling function
> which emails me with any SQL errors that are generated from my calls
> to DBI.

Have you considered using eval {} instead?  It's much more OOish anyways.
eval { $db->prepare("select * from users"); $db->execute(); };
if ($@) {
    my $errorMaker = ErrorFactory->new();
    my $error = $errorMaker->createError($@);
    $error->handle_error();
}


> But that gets me thinking ... is this variable global for EACH
> instance of my module, or is it global across all instances of my
> module (i.e. static)? If PerlEx is running, and five people are
> accessing a script at once, all of which using my module, will they
> each have a unique copy of $last_query, or are they sharing?

First, in a non-mod_perl, enviornment, there would not be separate instances
of your module/class, because Perl is smart enough to check whether a class
has already been included, and doesn't "re-include" it, even if you include
another module that also includes the same module.  All instances of your
_objects_ are using the same class/module, therefore the global is indeed
"static" and shared among all your objects of the same class.

In a mod_perl enviornment, scripts are cached on a perl-child basis.  So,
no, you would not be able to share the global across different apache
children.

In most threaded enviornments (AOLServer for example), however, scripts are
cached only once, and are shared between threads.  So, the global _would_ be
shared between different threads in AOLServer.

                     -Mike






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

Date: Tue, 13 Mar 2001 05:16:20 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Assigning string from between two patterns?
Message-Id: <slrn9arsrk.ur1.tadmc@tadmc26.august.net>

Eric Bohlman <ebohlman@omsdev.com> wrote:
>Brian Glass <bglass@pgtv.com> wrote:
>> The text file is set up with data as follows:
>
>> <tag>data string</tag><tag2>another data string</tag2>
>
>> I need to be able to extract the text 'data string' and assign it to a 
>> scalar variable. 


>Assuming that this is not actual SGML (including HTML) or XML data in 
>which tag-represented elements can be nested, just use ordinary capturing 
>parentheses:
>
>if (/<tag>([^<]*)</tag>/) {
                   ^
                   ^ typo


   if (/<tag>([^<]*)<\/tag>/) {
                   
or

   if ( m#<tag>([^<]*)</tag>#) {


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: Tue, 13 Mar 2001 11:12:11 GMT
From: nmihai_2000@yahoo.com (Mihai N.)
Subject: Re: Detecting User Country in CGI Script
Message-Id: <90632FAC4MihaiN@24.1.64.32>

>Just keep in mind that a user with accept language="French" might sit in
>Switzerland, Belgium or Canada, a user with "English" might be in South
>Africa, NewZealand, or India, "Spanish" might be Spain or Mexico,
>traditional Chinese could be Taiwan or Hongkong (or even Singapore) and
>even "Portuguese" could come from the Iberian peninsula or from Brazil.
>Bottom line: don't try to deduce a location from a language. It simply
>doesn't work.

I don't say the language can give you a hint about country.
>> But if in fact what you wish to find out is the language

It seems that Yahoo (and others) solved the nazi problem by
filtering the requests based on IP address (tracking down the ISP).
Sure, you can use an anonymizer service, but this is something Yahoo
can't prevent. But they can prove they did "all that is technically 
possible", and don't have problems with the French law.
Shortly, I don't think it is a sure method to find out the country.

Mihai



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

Date: 13 Mar 2001 12:07:51 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: Does a merge function exist?
Message-Id: <98l2in$10$1@mamenchi.zrz.TU-Berlin.DE>

According to Lloyd Foss  <lfoss@myxa.com>:
> The problem is I am combining several timestamped logfiles together 
> and need the combined file to be in order.  The dirty solution is 
> to use sort:
> 
> @results = sort @log_1_contents, @log_2_contents, ... @log_N_contents;
> 
> However the logs are already in order so sort is inefficient.  I would 
> really like to merge the rather than sort.  Something on the order of:
> 
> @results = merge {merge_function} \@log_1_contents, \@log_2_contents...
> 
> The 'merge function' would be similar to sort's 'sort function' execpt 
> it would be a min or a max of the top element of each array in the
> list of array references rather than a compare.
> 
> Has such a function been written?  Or something similar available?
> 
> If not I will write it but I would prefer to not reinvent the wheel.

A CPAN search for "merge" shows this:

    File::Sort Sort a file or merge sort multiple files

Sounds like what you're asking for.

Anno


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

Date: Tue, 13 Mar 2001 06:22:14 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: Exp. Perl/CGI programmer needed 
Message-Id: <slrn9as0n6.ur1.tadmc@tadmc26.august.net>

waystar <waystar@home.com> wrote:

>Please accept my apologies if this post is not within the rules. 


Your post is not within the rules.

It is easier to apologize after the fact than to get
permission beforehand. This tells me something.


>Good help
>is hard to find these days:)


Your problem does not exempt you from the rules. You don't get to
take cuts in line just because you are "in a hurry".

Good help is especially hard to find for spammers and net abusers.

A deja/google search for your posting address is not encouraging
(though not in the Big 8, so who cares anyway).  This tells me a 
bit more.

ASCII art formatting and multiple consecutive punctuation marks
tell me yet more.


>Exp. Perl/CGI programmer needed for contract work. 


Nah. I'll pass.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: Tue, 13 Mar 2001 12:31:04 GMT
From: "June Young" <jyyoung@hfx.andara.com>
Subject: How to create c code from perl
Message-Id: <cqor6.54$Zx2.13390@sapphire.mtt.net>

Hi,

I am using perl5005 on VMS_Alpha7.21.
I tried to generate c code from perl using:
$> perl -MO=CC hll.pl
$>perl -MO=CC,-ohll.c hll.pl
- These two commands execute hll.pl instead of create .c file
I suspect the perl switch is case sensible, so I put quotes:
$>perl "=MO=CC" hll.pl
- This causes perl pause to wait for input.

Does anyone have idea how to make this work?

Thank,

June




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

Date: 13 Mar 2001 12:58:14 GMT
From: chris@cjx.com (Chris Allen)
Subject: How to use result of grep as an array?
Message-Id: <D4FFA2E881DCBCA7.A2ED3D4FB40A44EA.6773A32C6BA24BAC@lp.airnews.net>




The construct:

#!/usr/bin/perl -w
use strict;
 
my(@foo,@found);
@foo = ('aaa','aabbb','aaccc','ddd','eee');
@found = grep /^aa/,@foo;
print ("second found: $found[1]\n");


prints: second found: aabbb

like it should.

However, I would like to be able to do 
something like:

$found = ${grep /^aa/,@foo}[1]; # (obviously) doesnt work

using the result of grep directly as an array,
and saving me from having to use @found.

Is this possible, and if so can anybody point me
to the right documentation that would help me?

Thanks.






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

Date: 13 Mar 2001 13:06:36 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: How to use result of grep as an array?
Message-Id: <98l60s$2k8$2@mamenchi.zrz.TU-Berlin.DE>

According to Chris Allen <chris@cjx.com>:
> 
> 
> 
> The construct:
> 
> #!/usr/bin/perl -w
> use strict;
>  
> my(@foo,@found);
> @foo = ('aaa','aabbb','aaccc','ddd','eee');
> @found = grep /^aa/,@foo;
> print ("second found: $found[1]\n");
> 
> 
> prints: second found: aabbb
> 
> like it should.
> 
> However, I would like to be able to do 
> something like:
> 
> $found = ${grep /^aa/,@foo}[1]; # (obviously) doesnt work

 ...but

  $found = (grep /^aa/, @foo)[ 1]

does.

Anno


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

Date: Tue, 13 Mar 2001 12:43:19 GMT
From: cryofan@mylinuxisp.com (cRYOFAN)
Subject: I need to graph some data 
Message-Id: <3aae15b3.126289838@news3.mylinuxisp.com>

I have some data that I need to graph/plot on a web page viewable to
browsers.

It can be in a line graph or a bar chart form.

The data is in text files on a web server that offers free websites
and perl scripts. Basically I want to plot magnitude versus time.
I don't know exactly what perl modules the web server has available. I
know it has LWP::Simple because I am collecting the data via a bot
that runs from a perl CGI script.

Should I use javascript or perl or what? If perl, then what is the
easiest way to test if the server has the perl modules I need?

I don't know any javascript.

Any thoughts on how to best do this?

I am looking for the easiest way.

Thanks


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

Date: Tue, 13 Mar 2001 13:07:13 +0100
From: Thoren Johne <thoren@southern-division.com>
Subject: method alias
Message-Id: <MPG.15182be071ab592c989936@news.t-online.de>

recently we had the question in dclpm how one could alias a method name 
of an imported class.

usually this is done with a typeglob, but i had the (more or less ;) 
brilliant idea to do it the following way:

$Class::{'alias'} = $Class::{'methodname'};

it works (as far as i have been able to test it), but i feel somehow 
uneasy.

what may go wrong that way?

-- 
# Thoren Johne - 8#X - thoren@southern-division.com
# Southern Division Classic Bikes - www.southern-division.com
*human=*you=*me=*stupid=*DATA=>#print"Just Another Perl Hacker\n     8#X"
*stupid&&*human&&*me&&*you&&2&&seek*me,-118,1;read*you,$_,42;eval;__END__


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

Date: 13 Mar 2001 12:33:43 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: method alias
Message-Id: <98l437$2k8$1@mamenchi.zrz.TU-Berlin.DE>

According to Thoren Johne  <thoren@southern-division.com>:
> recently we had the question in dclpm how one could alias a method name 
> of an imported class.
> 
> usually this is done with a typeglob, but i had the (more or less ;) 
> brilliant idea to do it the following way:
> 
> $Class::{'alias'} = $Class::{'methodname'};
> 
> it works (as far as i have been able to test it), but i feel somehow 
> uneasy.
> 
> what may go wrong that way?

I'm sure someone will correct me if I'm wrong, but I believe the effect
of your method is exactly[1] the same the classical "*Class::alias =
*Class::methodname".  It aliases everything with the name "methodname"
to "alias", so %methodname, a filehandle methodname, etc. are all
aliased.  "*Class::alias = \ &class::methodname" selectively aliases
the method name only, which is usually preferable.

I'm sure there is a way to express selective aliasing using the
package stash directly.  "*Class::alias{ CODE} = \ &Class::methodname"
should do that, but it requires you to know more about the structure
of a stash than you normally need to know.  Appropriate assignment to
a typeglob encapsulates that knowledge.

Anno

[1] Well, almost. It seems that *Class::alias = *Class::methodname
    happens at compile time while your assignment happens at run time.


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

Date: Tue, 13 Mar 2001 15:36:40 +0300
From: "HB" <npecca@yahoo.com>
Subject: Re: Millisecond Time Help (Yes I've consulted the FAQ)
Message-Id: <98l554$qdq$1@serv2.vsi.ru>

Steven Morrow wrote in message <3AA3C4A2.19D49B47@interbulletin.com>...

> I'm trying to time stamp data entries, but second time
> is not of high enough resolution to be unique.
>
> I have consulted perlfaq8 which suggests using Time::HiRes to get time
> of day to fractional seconds, but have had problems with the module.
>
> I am using Windows NT 4.0 with Active Perl v5.6.0
> bulit for MSWin32-x86-multi-thread.

ppm install Time::HiRes




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

Date: Tue, 13 Mar 2001 13:43:34 +0000
From: Anthony Peacock <a.peacock@chime.ucl.ac.uk>
Subject: Re: Newbie SSI Time Format
Message-Id: <3AAE2406.230E1E69@chime.ucl.ac.uk>

PaAnWa wrote:
> 
> I am trying to insert the last date modified in my HTML pages.  The
> instructions provided by the webhosting company need interpreting...can you
> help?
> 
> <!--#config timefmt="strftime_formatting_string"-->
> 
> So, what does the bit in the quotes mean?  I want the formate to appear as
> Month day, Year - this means I need to convert the time using %B %d, %Y
> format, but I don't know how to put it all together.

As this is an Apache SSI directive perhaps the Apache docs could help
you:

http://httpd.apache.org/docs/howto/ssi.html

No Perl content here...


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

Date: Tue, 13 Mar 2001 07:39:58 -0600
From: "ac" <clarke@hyperformix.com>
Subject: Re: perl2exe performance problem
Message-Id: <uqpr6.292$VV4.58087@news.uswest.net>

I use PerlApp from Activestate, but I'll give you some educated guesswork.
PerlApp and Perl2Exe do not "compile" Perl, they bundle it together. You
will never see a performance gain by using these products.

Usually the bundling mechanism results in slower startup times. That is,
when
the exe is invoked, the required files that were bundled into the exe are
now
unbundled on the fly into a temp area. This will account for almost all of
your
slowdown.

For PerlApp there is an option to delete or not these temp files when the
exe runs. I haven't tried this but its likely that if you have this option
and
use it, the app will start up much quicker after the first time.

Good luck.

Allan

"Uwe Sprave" <uwe_sprave@hp.com> wrote in message
news:3AACF4F6.CB9F054F@hp.com...
> Hi
>
> I recently bought the perl2exe tool from www.indigostar.com to "compile"
> my perl application. Unfortunately the performance went dramatically
> down compared to the interpreted version.
>
> We see now a runtime of 5-6 seconds instead of 3! My perl application
> named sas.pl creates the source code of a HTML webpage and responds in 3
> seconds while being run as sas.pl interpreted by perl.exe (ActiveState
> Perl 5.6.0 623). If we use sas.exe instead, the performance is much much
> slower.
>
> Unfortunately the CPAN Time::HiRes timer does not compile with perl2exe
> (sas.pl does run fine) to make detailed performance analysis about
> loadtime, runtime etc.
>
> I have no idea, how to troubleshoot this problem further down. Maybe you
> have some experiences or thoughts that you like to share with me?
>
> Some details about my configuration:
> Webserver: Microweb (www.Indigostar.com)
> Perl: ActiveState 5.6.0 / 623
> Perl2exe: V4.03 (www.Indigostar.com)
>
> Commandline to compile:
> perl2exe -perloptions="-p2x_noshow_includes" -small -tiny sas.pl
>
> Files created with their size in bytes:
>    554.187 sas.exe
>     20.480 Base64.dll
>     28.672 Dumper.dll
>     20.480 Hostname.dll
>     24.576 IO.dll
>    643.072 p2x560.dll
>     77.824 POSIX.dll
>     86.016 re.dll
>     24.576 Socket.dll
>
> Any idea is welcome.
>
> regards,
>
> Uwe Sprave
> uwe_sprave@hp.com




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

Date: Tue, 13 Mar 2001 14:28:21 +0100
From: David Bouman <david.bouman@nl.xo.com>
Subject: puzzling do{} and map interaction
Message-Id: <3AAE2075.7099A7B2@nl.xo.com>


Consider these:

1)  $l = { map( ($_,1), qw( a b )) }      ; print(( ref($l) || $l ),
"\n" );

2)  $l = do{ { a => 1, b => 1 }}          ; print(( ref($l) || $l ),
"\n" );

3)  $l = do{ { map( ($_,1), qw( a b )) }} ; print(( ref($l) || $l ),
"\n" );

1 outputs "HASH"  (makes sense to me)
2 outputs "HASH"  (yup, been expecting that)
3 outputs "4"     (huh ?)

Why ?

--
David Bouman (using perl, version 5.005_03 built for sun4-solaris )


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

Date: 13 Mar 2001 13:54:45 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: puzzling do{} and map interaction
Message-Id: <98l8r5$6k7$1@mamenchi.zrz.TU-Berlin.DE>

According to David Bouman  <david.bouman@nl.xo.com>:
> 
> Consider these:
> 
> 1)  $l = { map( ($_,1), qw( a b )) }      ; print(( ref($l) || $l ),
> "\n" );

Here you call map in a list context, as provided by the {} hashref
constructor.
 
> 2)  $l = do{ { a => 1, b => 1 }}          ; print(( ref($l) || $l ),
> "\n" );

This is a hashref constructor basically by itself.  Wrapping a do{}
around it doesn't change its behavior.

> 3)  $l = do{ { map( ($_,1), qw( a b )) }} ; print(( ref($l) || $l ),
> "\n" );

Here, the inner pair of {} is interpreted as an extra pair of block
braces, not a hashref constructor.  Both interpretations are possible;
why Perl chooses the one it does is anybody's guess.

The effect is, that scalar context propagates right though to map(),
so it returns the number of elements it has produced.

> 1 outputs "HASH"  (makes sense to me)
> 2 outputs "HASH"  (yup, been expecting that)
> 3 outputs "4"     (huh ?)
> 
> Why ?

I think I have answered the "how".  The "why" is open to discussion.

If you want to enforce the interpretation you seem to expect, add a
single "+" to the leading brace:

$l = do{ +{ map( ($_,1), qw( a b )) }} ; print(( ref($l) || $l ), "\n" );
HASH

Anno

Anno


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

Date: Tue, 13 Mar 2001 05:51:22 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: RE Doubt
Message-Id: <slrn9arut9.ur1.tadmc@tadmc26.august.net>

Chandramohan Neelakantan <Chandramohan_member@newsranger.com> wrote:
>
>What is the diffrence between using '+' inside  square brackets and using it
                                                 ^^^^^^^^^^^^^^^

Those are properly called "character classes".


>outside the same?


You have a question about a language (char classes) inside of a
language (regexes) inside of a language (Perl).

This often causes confusion, as you might expect.

You need to determine which language you are speaking at the point
where you use a construct.


in Perl + means "addition".

in regexes + means "one or more of the previous thing".

in char classes it means "match a plus character".


[ Note that "square brackets" are even more overloaded than + is ... ]


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: 13 Mar 2001 11:31:08 GMT
From: abigail@foad.org (Abigail)
Subject: Re: reg exp question
Message-Id: <slrn9as17s.435.abigail@tsathoggua.rlyeh.net>

zawy (zawy@yahoo.com) wrote on MMDCCLI September MCMXCIII in
<URL:news:3aad7c16.48202760@news.knology.net>:
** I thought I knew REs.
** 
** $a=12
** $b=12
** 
** The following return TRUE
** $a=~/^$b/
** $a=~/^$b$/
** $a=~/$b$/
** 
** The following returns FALSE
** $a=~/$b/
** 
** Why FALSE?


Because "FALSE" is a true value? I dunno. 

    $ perl -wle '$a=12; $b=12; print "TRUE" if $a =~ /$b/'
    TRUE



Abigail
-- 
perl -e '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / 
         % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %;
         BEGIN {% % = ($ _ = " " => print "Just Another Perl Hacker\n")}'


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

Date: 13 Mar 2001 13:02:33 +0000
From: nobull@mail.com
Subject: Search and replace several targets at once (was: Can a regex do this?)
Message-Id: <u9u24x95zq.fsf@wcl-l.bham.ac.uk>

blahblah <blah@blah.com> writes:

> I am looking for a regex

No, you are looking for a statement.  A regex is just, er, a regex.

> that will do two replacements on the same
> line. For example:
> 
> $test = "test1 test2 test3";
> $test =~ s/1/a/g;
> $test =~ s/2/b/g;
> $test =~ s/3/c/g;

Er excuse me, that's three.

require 5.6.0;
$test =~ s/(1)|(2)|(3)/("a","b","c")[$#- - 1]/eg;

BTW: Your original approach is more readable and probably more
efficient too.  (See numerous previous threads giving benchmark
results for the two approaches).

Of course if all your LHS targets are literal strings and the set of
targets can be matched by a simple regex as in this case then you can do: 

my %replacements = ( 1 => 'a', 2 => 'b', 3 => 'c' );
$test =~ s/([1-3])/$replacements{$1}/eg;

> Thanks for any input, regexes are cool!

Usenet search engines are cool too - this question has been asked and
answered a few times before!

Of course the utility of Usenet search engines is signficantly impared
when selfish people are too lazy to bother think up informative
subjects for their threads.

-- 
     \\   ( )
  .  _\\__[oo
 .__/  \\ /\@
 .  l___\\
  # ll  l\\
 ###LL  LL\\


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

Date: 13 Mar 2001 11:42:36 GMT
From: abigail@foad.org (Abigail)
Subject: Re: subroutine recursion?
Message-Id: <slrn9as1tc.435.abigail@tsathoggua.rlyeh.net>

Christian Meisl (meisl@amvt.tu-graz.ac.at) wrote on MMDCCLI September
MCMXCIII in <URL:news:m3vgpeyoqi.fsf@famvtpc59.tu-graz.ac.at>:
{} Jeff Davis <jdavis@dynworks.com> writes:
{} > #!/usr/bin/perl
{} > 
{} > sub factorial($);
{} > print &factorial(6); print "\n";
{} > 
{} > 
{} > sub factorial($) {
{} >          $x = shift;
{} >          print "x: $x\n";
{} >          if($x == 1) {
{} >                  print "r: 1\n"; # debugging, returned expected
{} >                  return 1;
{} >          }
{} >          else {
{} >                  print "r: $x\n"; # debugging, returned expected
{} >                  return ( $x * &factorial($x-1) ); # returned UNexpected
{} >          }
{} > }
{} 
{} I am not a perl guru, but for my eyes the dollar sign in the sub
{} declaration seems to be wrong. The following should work:

The dollart sign isn't wrong at all. It's a prototype. Of course,
because & is used to call the function, the prototype isn't actually
checked, but that doesn't make the prototype wrong.

{} #! /usr/bin/perl -w
{} use strict;
{} 
{} sub factorial {
{}     my $x = shift; # Get first argument into $x
{}     return 1 if $x == 1; # &factorial(1) == 1
{}     return $x * &factorial(--$x); # Otherwise do recursion
{} }
{} 
{} print &factorial(6)."\n";


Which prints.... 120. And that isn't the factorial of 6. Your problem
is the use of --$x, which is a pre-increment. Which will increment $x
some time before factorial is called. But there's no garantee it will
be incremented before the value of $x is fetched for the multiplication.



Abigail


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

Date: Tue, 13 Mar 2001 13:22:18 +0100
From: "Jonas Nilsson" <jonni@ifm.liu.se>
Subject: Re: subroutine recursion?
Message-Id: <98l3al$m7i$1@newsy.ifm.liu.se>

I suggest an improvement.

> print "trying $ARGV[0] ",factorial($ARGV[0]), "\n";
>
> sub factorial{
>         return 1 if $_[0] == 1;
>         return $_[0] * factorial ($_[0] - 1);
> }

Will hang for $ARGV[0]<=0...
My suggestion:

sub factorial{
        return 1 if $_[0] == 0;
        return undef unless $_[0] >= 0;
        return $_[0] * factorial($_[0] - 1);
}





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

Date: Tue, 13 Mar 2001 06:08:58 -0500
From: tadmc@augustmail.com (Tad McClellan)
Subject: Re: subroutine recursion?
Message-Id: <slrn9arvu9.ur1.tadmc@tadmc26.august.net>

Jeff Davis <jdavis@dynworks.com> wrote:

>This seems a simple problem, but how do you make a recursive subroutine? 
                                                              ^^^^^^^^^^

I would begin with the paragraph in perlsub.pod that starts with
"Subroutines may be called recursively.", but you have surely
already seen that.

But that isn't really your problem. You have already created a
recursive subroutine below!


>I have my code below that didn't work. 
                           ^^^^^^^^^^^

That information is not very helpful for debugging purposes.

What does "didn't work" mean?

   dumps core
   syntax error
   makes no output
   too much output
   too little output
   incorrect output
   output's OK but want it arranged differently
   infinite loop
   emits smokes from vents
   ...


>I was trying to make a simple 
>"dircalc" program that would calculate the size of the contents of a 
>directory. I realized that I didn't know how to recurse, 


Well you don't need to know how to recurse to get _that_ job done.
Just use the File::Find module that ships with the perl distribution.
It does recursive dir walking for you:

   perldoc File::Find


>so I tried 
>making the simple case below (factorial calculator function):


But let's continue strictly as a learning experience...


>#!/usr/bin/perl


Problems already. You should ask for all the help you can get.
perl itself would have pointed out your problem if you had only
asked it to help you.

You ask perl to help you find common mistakes by enabling warnings
and strictures. The first two lines of all of your Perl programs
should be:

   #!/usr/bin/perl -w
   use strict;

Type:

   perldoc strict

to see what effect it has.


>sub factorial($);
              ^^^
>print &factorial(6); print "\n";
       ^

Read up on what happens to prototypes when the function is
called with an ampersand. Then fix it so that the prototype
is not a no-op as it is above.

Beginning Perl programmers should probably not mess with
using prototypes.


>sub factorial($) {
>         $x = shift;
          ^^

"use strict" would have prevented your error there.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: Tue, 13 Mar 2001 12:59:20 GMT
From: pjlees@ics.forthcomingevents.gr (Philip Lees)
Subject: Re: subroutine recursion?
Message-Id: <3aae1911.83061215@news.grnet.gr>

On 13 Mar 2001 11:42:36 GMT, abigail@foad.org (Abigail) wrote:

Excuse the lese majeste:

>is the use of --$x, which is a pre-increment. Which will increment $x
>some time before factorial is called. But there's no garantee it will
>be incremented before the value of $x is fetched for the multiplication.

<pedant>

s/increment/decrement/g

</pedant>

Phil
--
@x=split//,'Just another Perl decoder,';split//,'*'x@x;%i=split/=/,
'AA=a=aa= =1=,';for$i(0..$#x){$_[$i]=chr($=+5);while($_[$i]ne$x[$i])
{$_[$i]=$i{$_[$i]}if$i{++$_[$i]};print@_,"\r";while(rand!=rand){}}}
Ignore coming events if you wish to send me e-mail


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

Date: 13 Mar 2001 14:36:13 +0100
From: Christian Meisl <meisl@amvt.tu-graz.ac.at>
Subject: Re: subroutine recursion?
Message-Id: <m3puflzt82.fsf@famvtpc59.tu-graz.ac.at>

abigail@foad.org (Abigail) writes:
> {}     return $x * &factorial(--$x); # Otherwise do recursion

> Which prints.... 120. And that isn't the factorial of 6. Your problem
> is the use of --$x, which is a pre-increment. Which will increment $x
> some time before factorial is called. But there's no garantee it will
> be incremented before the value of $x is fetched for the multiplication.

Ups, ...

return $x * &factorial($x-1);

should work instead...

Regards,
Christian

-- 
Christian Meisl <meisl@amvt.tu-graz.ac.at>        www.amft.tu-graz.ac.at
   Inst. f. Apparatebau, Mech. Verfahrenstechnik und Feuerungstechnik
------- If you can't beat your computer at chess, try kickboxing -------
PGP fingerprint:      DF48 2503 0411 F0EF 149C  851B 1EF0 72B9 78B6 034A


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

Date: Tue, 13 Mar 2001 11:47:27 +0000
From: "Donal K. Fellows" <fellowsd@cs.man.ac.uk>
Subject: Re: Tk based alarm clock
Message-Id: <3AAE08CF.F6A0B026@cs.man.ac.uk>

Phil Ehrens wrote:
> He means same system --

Sort of...

> Let's see... mmm... ps -Ao fname,vsz |grep tclsh... pmap 6514...
> mumble mumble... count on fingers...
> 
> Looks like between 250 and 300 Kb for each new interp on both
> Linux and Solaris.  The rest is .so's.

No.  You must remember that you can have several interpreters per thread
and several threads per process[*].  The overhead for a new interpreter
is only a few kilobytes (I've not measured in detail) since it can share
machine code with the other processes on the system, much more with the
rest of its process and stacks with other interps in the same thread.

Interpreters are 460 bytes each (32-bit arch, no debug) before accounting
for script sizes or hashtable contents.

Donal.
[* If built multi-threaded, otherwise you've got exactly one thread per
   Tcl/Tk process which is currently the most common configuration. ]
-- 
Donal K. Fellows    http://www.cs.man.ac.uk/~fellowsd/    fellowsd@cs.man.ac.uk
"I wouldn't just call you wrong.  I'd go further and call you an argumentative
 net-kook idiot who can't do his own research before opening his mouth and
 yammering bullshit."                -- Theo de Raadt <deraadt@zeus.theos.com>


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

Date: Tue, 13 Mar 2001 13:53:05 -0000
From: "The NewsBrowser" <nbr@newsbrowser.com>
Subject: Whoops!
Message-Id: <98l8nu$2bmvv$1@ID-18325.news.dfncis.de>

Oh dear, sorry about the multiple posts... I had thought that my
news client hadn't sent out my first post when in fact it had.

--
Akin

email: akin at aksoto dot idps dot co dot uk







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

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


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