[23484] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 5697 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed Oct 22 18:05:53 2003

Date: Wed, 22 Oct 2003 15:05:11 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Wed, 22 Oct 2003     Volume: 10 Number: 5697

Today's topics:
        All possible combinations of two lists <null@null.com>
    Re: All possible combinations of two lists <jurgenex@hotmail.com>
    Re: c programmer in need of perl advise <grazz@pobox.com>
    Re: c programmer in need of perl advise <grazz@pobox.com>
    Re: c programmer in need of perl advise (Randal L. Schwartz)
    Re: Client/Server Help! (nospam)
    Re: Client/Server Help! <flavell@ph.gla.ac.uk>
    Re: compress folders <jgibson@mail.arc.nasa.gov>
        file redirect within back ticks not working <abc@nowhere.com>
        FileHandle::Unget 0.11 released <newspost@coppit.org>
    Re: Further on Taint - exact code that has the problem (Ben)
    Re: Further on Taint - exact code that has the problem (Ben)
    Re: Further on Taint - exact code that has the problem <xx087@freenet.carleton.ca>
        grepmail 5.22 released <newspost@coppit.org>
        Mail::Mbox::MessageParser 1.12 released <newspost@coppit.org>
    Re: my first perl script! <willema@student.ethz.ch>
    Re: my first perl script! <willema@student.ethz.ch>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Wed, 22 Oct 2003 20:52:29 GMT
From: "Ed W." <null@null.com>
Subject: All possible combinations of two lists
Message-Id: <h6Clb.153992$xx4.27717890@twister.neo.rr.com>

I am trying to write a script to list all the possible combinations of gift
certificate denominations for a given order total. For example, if a person
has $25.00 to spend, they can purchase 1 $25.00 certificate, 2 $10.00
certificates and 1 $5.00 certificate, etc.

The code I have so far is listed below. I am struggling with all of the
possible combinations. I think I have to recurs through each of the items,
but I can't figure out how to do that. Can anyone post some relevant
sections in the docs, or other examples similar to this?

use Data::Dump qw(dump);
use strict;

my @denoms = sort { $a <=> $b } qw(25 10 5 50);
my @totals = qw(25 40);

my %results;

# Loop through each value
foreach my $total_value (@totals) {

 my %temp;
 my $remainder = $total_value;
 foreach my $denom (@denoms) {

  # Check each denomination and see if it is evenly divisible.
  if ( ($total_value % $denom) == 0 ) {
   push(@{$results{$total_value}},
    { $denom => ($total_value/$denom) });
  }

  # Add one denomination to a local count
  if ($total_value > $denom) {
   $temp{$denom} += 1;
   $remainder -= $denom;
  }
 }
 push(@{$results{$total_value}}, \%temp) if ($remainder == 0);
}
print dump(\%results);


Thanks
-Ed W.




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

Date: Wed, 22 Oct 2003 21:32:38 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: All possible combinations of two lists
Message-Id: <WHClb.18185$Y1.1477@nwrddc03.gnilink.net>

Ed W. wrote:
> I am trying to write a script to list all the possible combinations
> of gift certificate denominations for a given order total. For
> example, if a person has $25.00 to spend, they can purchase 1 $25.00
> certificate, 2 $10.00 certificates and 1 $5.00 certificate, etc.
>
> The code I have so far is listed below. I am struggling with all of
> the possible combinations. I think I have to recurs through each of
> the items, but I can't figure out how to do that. Can anyone post
> some relevant sections in the docs, or other examples similar to this?

Your problem has little to do with Perl and you won't find anything in the
doc's that is relevant to your problem.

But it is a very famous example in computer science for an NP complete
problem.
Try to do some research on the knapsack problem. There are _many_  algorithm
and ideas in computer literature about it.
You should be able to adapt those solutions with almost no modification for
your specific problem.

jue




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

Date: Wed, 22 Oct 2003 18:26:53 GMT
From: Steve Grazzini <grazz@pobox.com>
Subject: Re: c programmer in need of perl advise
Message-Id: <NZzlb.14165$Vf7.74@nwrdny02.gnilink.net>

A. Sinan Unur <asu1@c-o-r-n-e-l-l.edu> wrote:
> mikedeskevich@yahoo.com (Mike Deskevich) wrote:
> > $ct=0;
> > while (<DATAFILE>)
> > {
> >   ($xvalue[$ct],$yvalue[$ct])=split;
> >   $ct++;
> > }
> 
> In this case, the $xvalue and $yvalue arrays are constantly being 
> resized.

I think "constantly" is too strong -- when an array needs to be
extended, perl will allocate (roughly) enough space for its size
to double.

Calling push() 10,000 times will only resize the array twelve 
times, and, unlike "$#x = $BIGNUM", the end of the array will never
be filled with undefined elements.

-- 
Steve


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

Date: Wed, 22 Oct 2003 18:34:19 GMT
From: Steve Grazzini <grazz@pobox.com>
Subject: Re: c programmer in need of perl advise
Message-Id: <L4Alb.14191$Vf7.12877@nwrdny02.gnilink.net>

Greg Patnude <gpatnude@adelphia.net> wrote:

[ TOFU was lost under the signature ]

> Its called "slurping" a file -- the so-called "pros" claim it is not really
> "recommended" but I do it all the time with absolutely no consequence and no
> obvious performance hit until the files exceed 6 MB or so ...

Presumably this scaling problem is what they had in mind.
 
>  if (open (DATA, "$FILENAME")) {
> 
>     @DATA = <DATA>;
> 
> }

And anyway, how does this help the OP, who needs the first bit of each
line to go in one array and the second to go in another?

Also, you might want to reconsider using the special DATA filehandle
like this.

-- 
Steve


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

Date: Wed, 22 Oct 2003 19:00:23 GMT
From: merlyn@stonehenge.com (Randal L. Schwartz)
To: "Greg Patnude" <gpatnude@adelphia.net>
Subject: Re: c programmer in need of perl advise
Message-Id: <0a349e0bb2edf9b6797fa1160067b47c@news.teranews.com>

>>>>> "Greg" == Greg Patnude <gpatnude@adelphia.net> writes:

Greg> $#ARRY will give you the number of array elements also ...

No, that gives the highest index, which is one less than the
number of elements (remember the "0" element).

$#ARRAY is useful when you need an index range:

        for (0..$#ARRAY) { ... do something with $ARRAY[$_] ... }

But @ARRAY in a scalar context gives the number of elements.

        if (@ARRAY > 3) { ... more than 3 elements ... }
        while (@ARRAY) { ... keep doing until @ARRAY is empty ... }

Note that "scalar(@ARRAY)" is merely a notation for "use @ARRAY
in a scalar context", although 90% of the time, the "scalar( ... )" part
isn't necessary, and if you add it unnecessarily, I shall have to come
over there and whack you on the head a few times as punishment. :)

print "Just another Perl hacker,"

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!


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

Date: Wed, 22 Oct 2003 13:58:49 -0400
From: "bob Smith" <bobsmith(nospam)@bobsmith.com>
Subject: Re: Client/Server Help!
Message-Id: <bn6ikj$smf$1@news1.usf.edu>

You the man.  Thank you very much.  I just needed that shutdown.  I was able
to incorparate that in to my programs and it worked.  That was greatly
appreciated.

"A. Sinan Unur" <asu1@c-o-r-n-e-l-l.edu> wrote in message
news:Xns941C86AC06DAasu1cornelledu@132.236.56.8...
> "A. Sinan Unur" <asu1@c-o-r-n-e-l-l.edu> wrote in
> news:Xns941C863C98EEDasu1cornelledu@132.236.56.8:
>
> > my $msg = join("\n", @_) || 'Hi there server dude ...';
>
> Please replace this line with
>
> my $msg = 'Hi there server dude ...';
>
> in the example in my previous response.
>
> -- 
> A. Sinan Unur
> asu1@c-o-r-n-e-l-l.edu
> Remove dashes for address
> Spam bait: mailto:uce@ftc.gov




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

Date: Wed, 22 Oct 2003 21:26:43 +0100
From: "Alan J. Flavell" <flavell@ph.gla.ac.uk>
Subject: Re: Client/Server Help!
Message-Id: <Pine.LNX.4.53.0310222123260.11322@ppepc56.ph.gla.ac.uk>

On Wed, 22 Oct 2003, Brian McCauley wrote:

> I have a nagging doubt that there's also a problem using "\n" across
> platforms.

perldoc perlport encourages the use of CRLF (\015\012) when doing
sockets, for its benefits in terms of cross-platform working.  It's
also a practice that's heavily supported by the Internet RFC protocols
for interworking compatibility.  I'm sure you're right to be doubtful
about a logical notation ("\n") whose physical embodiment differs
between platforms.

(but I'm sure you knew that already)


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

Date: Wed, 22 Oct 2003 13:25:41 -0700
From: Jim Gibson <jgibson@mail.arc.nasa.gov>
Subject: Re: compress folders
Message-Id: <221020031325418817%jgibson@mail.arc.nasa.gov>

In article <bn6eam$j3h$0@pita.alt.net>, Josie Armindez <ja@nospam.foo>
wrote:

> I want to go into /home and tar all of the user directories.
> Here is what I have so far:
> 

Add these to get help from perl:

   use strict;
   use warnings;

> my $backup;
You don't need to declare $backup here

> my $count;
> $count = @folders;

Combine these: 

   my $count = @folders;

> my @folders = `ls`;

You must already be in /home, yes?

> 
> foreach ( @folders ) {

The name of entities in /home is now in the variable $_. If you aren't
sure of what you are doing, it might be best to use explicit variables:

   foreach my $dir ( @folders ) {

You might want to test for directories:

   if( -d $dir ) {

> #$backup = `tar -cvf @folders.tar @folders`; # this doesn't work

You can put together a tar command using $dir now:

      my $cmd = "tar -cvf $dir.tar $dir";

and execute it without capturing the output:

      system($cmd);

or with capture:

      my @lines = `$cmd`;
   }

> 
> }
> 
> $test_count = @folders;
> print 'total ', scalar @folders, " folders\n";
> 
> 
> How can I perform the tar operation on each of the folders in the array?
> 
> TIA
> Josie
> 
> 

(Above code was all untested)


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

Date: Wed, 22 Oct 2003 21:04:07 GMT
From: ktom <abc@nowhere.com>
Subject: file redirect within back ticks not working
Message-Id: <bhClb.4264$pJ1.1517@twister.austin.rr.com>

from with a perl script this line does not work

`sed -e 1,14d $file >> /tmp/junk`;

it seems the redirect does not work.



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

Date: Wed, 22 Oct 2003 17:15:40 GMT
From: David Coppit <newspost@coppit.org>
Subject: FileHandle::Unget 0.11 released
Message-Id: <Hn6Asz.xBJ@zorch.sf-bay.org>

NOTE: This new module answers a long-standing question: "How can I (portably)
un-read from a filehandle?" It should be fully compatible with FileHandle...
Please let me know if you can find a situation in which it doesn't work.

Description:
- FileHandle::Unget is a drop-in replacement for FileHandle which allows more
  than one byte to be placed back on the input. It supports an ungetc(ORD)
  which can be called more than once in a row, and an ungets(SCALAR) which
  places a string of bytes back on the input.

Download:
- You can download FileHandle::Unget from CPAN:
  http://www.cpan.org/authors/id/D/DC/DCOPPIT/FileHandle-Unget-0.11.tar.gz
- Until the file propagates to the mirrors, you can use the following URL:
  http://prdownloads.sourceforge.net/fh-unget/FileHandle-Unget-0.11.tar.
gz

Changes:
- Fixed uninitialized value warnings
- Created SourceForge project

See the README for additional notes.

A complete change log is at:
- http://fh-unget.sourceforge.net/CHANGES

Regards,
David




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

Date: 22 Oct 2003 12:03:19 -0700
From: 2stormts@nemontel.net (Ben)
Subject: Re: Further on Taint - exact code that has the problem
Message-Id: <5c8f38ff.0310221103.408f12df@posting.google.com>

Glenn Jackman <xx087@freenet.carleton.ca> wrote in message news:<slrnbpcvsk.9ko.xx087@smeagol.ncf.ca>...
> Ben <2stormts@nemontel.net> wrote:
> >   $rez = system($command);
>  [...]
> >  pogmaker absolutely will not run.
> 
> Find out why:
> 
>     if ($rez != 0) {
>         print "<p>'$command' exits status: ", $rez/256, "</p><pre>$!</pre>";
>     }

$rez = 0

$! = ""

Next idea? :)

--Ben


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

Date: 22 Oct 2003 12:29:30 -0700
From: 2stormts@nemontel.net (Ben)
Subject: Re: Further on Taint - exact code that has the problem
Message-Id: <5c8f38ff.0310221129.4f7a3718@posting.google.com>

Louis Erickson <wwonko@rdwarf.com> wrote in message news:<bn4fjg$6t8$1@holly.rdwarf.com>...
> Ben <2stormts@nemontel.net> wrote:
> :  $cmd = "pogmaker";
> :  $command = "$cmd $part $befo $fute $cols $redd >output.txt &";
> :  $command =~ /(.*)/;
> :  $command = $1;
> :  $ENV{"PATH"}="/bin:/usr/bin";
> :  delete @ENV{'IFS','CDPATH','ENV','BASH_ENV'};
> :  # print "Taint checks seem to be on<br>"
> :  # unless eval { local $^W; unlink "$^X$^T"; 1 };
> :  $rez = system($command);
>  
> : FYI, the print "Taint.... does not indicate that taint is on by
> : printing.
> 
> Then I suspect taint is not on.  Why do you think taint is on?

The behaviour - runs if used in ('cmd',$parm,$parm,etc) form, but not
if in ("$cmd $parm $parm etc.") form. This behavior is described
fairly closely in perlsec as a consequence of taint being in effect.
No such behavior is described in, or referenced from,
functions/system(), however, which I consider a rather severe
oversight. Taint is not mentioned or referenced either, which it
probably should be.

<ASIDE> I find the perl documentation to be pretty poor in general...
WAY too many assumptions made about what the reader knows, not enough
example code and often, what example code you find there is pretty
darned opaque. I'd offer to contribute, I actually write pretty good
documentation, but the fact that I'm still looking IN the perl
documentation more often than not probably makes me a poor
candidate... sure wish someone would give that stuff a professional
going over. I love perl, but the docs... ugh.</ASIDE>

Also, in perlsec, the following remark is found near the top:

"Perl automatically enables a set of special security checks, called
taint mode, when it detects its program running with differing real
and effective user or group IDs."

 ...the implication seems to be that taint mode could get turned on
very late, right at the point where the command is invoked, even if it
wasn't on previously. That also leads me to think that taint might be
screwing with things, even if the latest check prior to launch I can
make clearly indicates it isn't.

> : pogmaker is in /usr/bin, has execute permission for anyone, owned by
> : root.
>  
> : pogmaker absolutely will not run.
> 
> Why not?

Dunno. That's what this is all about. :)

>  Have you checked the return values from system?

Yes, indeed. system() returns 0, and $! is empty.

>  See perldoc -f system to get how to decode the error values from
> system to make sure it's working,

Not much decoding required. 0 is 0 even when you divide it by 256. :)

> and check your server logs for
> any messages to stderr indicating possible problems from
> your program itself.

None. Also no indication that the program is running when diagnostics
like create a flag file, sleep for a while so I can look in the
process list are added... it's simply not running. When it does run,
it can run even with no parameters and come up with sensible (but
pointless) output. If I call it as system('cmd',$parm,$parm) it runs
perfectly (but runs too long, I need to fork it either from the
shell's interpretation of & or directly.) If I hack the command to
immediately exit(1), I get 256 as expected in the perl script, as a
return from system(). Change the perl to system("$cmd $parm $parm etc)
and I get nothing.

Additional info that might bear on people thinking on why something
might not run: My program is compiled from c, is relatively small
(about 29k) and is running in a 2 GHz, 1 Gb RH9 system with tons of
available resources. Once it is running, it talks to the PostgreSQL
postmaster in the usual ways, but that's way, way after I put the
diagnostics in - no dependance upon PostgreSQL servers involved, for
absolute certain. I can't get the first line of code to run even when
it's exit(1) if the system call is used with one parameter for shell
evaluation.

Thanks for your previous and potential future response(s.)

--Ben


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

Date: 22 Oct 2003 19:53:04 GMT
From: Glenn Jackman <xx087@freenet.carleton.ca>
Subject: Re: Further on Taint - exact code that has the problem
Message-Id: <slrnbpdo23.9ko.xx087@smeagol.ncf.ca>

Ben <2stormts@nemontel.net> wrote:
>  Glenn Jackman <xx087@freenet.carleton.ca> wrote in message news:<slrnbpcvsk.9ko.xx087@smeagol.ncf.ca>...
> > Ben <2stormts@nemontel.net> wrote:
> > >   $cmd = "pogmaker";
> > >   $command = "$cmd $part $befo $fute $cols $redd >output.txt &";
> > >   $command =~ /(.*)/;
> > >   $command = $1;
> > >   $rez = system($command);
> >  [...]
> > >  pogmaker absolutely will not run.
> > 
> > Find out why:
> > 
> >     if ($rez != 0) {
> >         print "<p>'$command' exits status: ", $rez/256, "</p><pre>$!</pre>";
> >     }
>  
>  $rez = 0
>  $! = ""

Someone else pointed this out in the parallel thread:  because you run
$command in the backgrounded, you cannot know its exit status.  system()
will return successfully immediately because the forked /bin/sh process
does.  Note that the system() docs say:
    If there is only one scalar argument, the argument is checked for
    shell metacharacters, and if there are any, the entire argument is
    passed to the system's command shell for parsing (this is "/bin/sh
    -c" on Unix platforms, but varies on other platforms).  

Similarly, if you open the command as a pipe, open(X,"$command |"), you
cannot know the exit status until you close() it.

As to why your command is not running, does the web server's user have
permission to write to output.txt?  Have a look at what's happening on
stderr:
   $command = "$cmd $part $befo $fute $cols $redd >output.txt 2>output.err &";

-- 
Glenn Jackman
NCF Sysadmin
glennj@ncf.ca


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

Date: Wed, 22 Oct 2003 17:19:33 GMT
From: David Coppit <newspost@coppit.org>
Subject: grepmail 5.22 released
Message-Id: <Hn6Hq8.1n8n@zorch.sf-bay.org>

grepmail 5.22 released

Description:
- grepmail is a Perl program that searches a normal or compressed mailbox
  (gzip, bzip2, or tzip) for a given regular expression and returns those
  emails that match the query. It also supports searches constrained by date
  and size.

Download:
- You can download grepmail from CPAN:
  http://www.cpan.org/authors/id/D/DC/DCOPPIT/grepmail-5.22.tar.gz
- Until the file propagates to the mirrors, you can use the following URL:
  http://prdownloads.sourceforge.net/grepmail/grepmail-5.22.tar.gz

Changes:
- X-Mailfolder header no longer has a line number when -n is used.
- New -B flag prints abbreviated headers
- Headers spanning multiple lines are now printed correctly in warnings and
  such.
- Fixed a spurious warning which would be printed if caching was not enabled.
- grepmail will now disable caching if the caching version of
  Mail::Mbox::MessageParser can not be loaded, instead of exiting.

See the README for additional notes on complex queries, and generation of
message IDs.

A complete change log is at:
- http://grepmail.sourceforge.net/CHANGES

Regards,
David




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

Date: Wed, 22 Oct 2003 17:17:50 GMT
From: David Coppit <newspost@coppit.org>
Subject: Mail::Mbox::MessageParser 1.12 released
Message-Id: <Hn6Hpu.16Gu@zorch.sf-bay.org>

Description:
- Mail::Mbox::MessageParser is a feature-poor but very fast mbox parser. It
  uses the best of three strategies for parsing a mailbox: either using cached
  folder information, GNU grep, or highly optimized Perl.

Download:
- You can download Mail::Mbox::MessageParser from CPAN:
  http://www.cpan.org/authors/id/D/DC/DCOPPIT/Mail-Mbox-MessageParser-1.12.tar.g
z
- Until the file propagates to the mirrors, you can use the following URL:
  http://prdownloads.sourceforge.net/m-m-msgparser/Mail-Mbox-MessageParser-1.12.
tar.gz

Changes:
- Added "perl Makefile.PL" version checks for external programs like grep.
- Fixed a typo in the documented synopsis
- Implemented a portable ungetc version of FileHandle, and changed this module
  to use it instead of IO::String. This will hopefully fix the
  system-dependent bugs in the last release.
- Improved compatibility with Windows. (Cygwin works, but we're still not
  there yet for Windows command shell.)
- Streamlined installation for cases where caching is not enabled in
  Mail::Mbox::MessageParser.

See the README for additional notes.

A complete change log is at:
- http://m-m-msgparser.sourceforge.net/CHANGES

Regards,
David




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

Date: Wed, 22 Oct 2003 21:37:05 +0200
From: "Matthias Wille" <willema@student.ethz.ch>
Subject: Re: my first perl script!
Message-Id: <pan.2003.10.22.19.37.01.168653@student.ethz.ch>

Am Mon, 20 Oct 2003 11:30:32 +0200 schrieb Desmond Coughlan:

> le 20 Oct 2003 00:34:47 -0700, dans l'article <3395b56f.0310192334.a66a044@posting.google.com>, Matthias Wille <m.wille@gmx.ch> a dit ... 
> 
>> I just started to learn perl and wrote my first program today
> 
> Just as a matter of interest..how long have you been doing Perl ?  I ask
> because I've been working with some Perl books and online tutorials for
> about three months, now (on and off, admittedly, as I have other
> priorities), and I can _just about_ understand 'hello world!'
> 
> So if you tell me you started last week, I'm going to be _very_ depressed.


I started about 1 Week ago with perl programming and I think i got the
main principles by now. But I'm a computer scientist, so I already have
experience with programming and understand the basic programming concepts.
So learning a new programming language is just a matter of learning new
syntax, although Perl has quite some constructs I have never seen in other
languages.... very interesting!

Greetings
Matthias


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

Date: Wed, 22 Oct 2003 22:47:19 +0200
From: "Matthias Wille" <willema@student.ethz.ch>
Subject: Re: my first perl script!
Message-Id: <pan.2003.10.22.20.47.17.739594@student.ethz.ch>

Am Mon, 20 Oct 2003 11:19:46 +0000 schrieb Tassilo v. Parseval:

Thanks for your code review and your tips. You were very helpful!


> $cwd is now a global variable. This has some other implications as well,
> but for now make the variable a lexical one:
> 
>     my $cwd = cwd();
> 
> This is a requirement of strict. It demands that you declare any
> variable you are going to use. Thus it catches a lot of typoes.


Actually I was aware of the 'my' and the whole scoping thing but I thought
it would be cooler not to use it... :-) guess I have still much to learn..


>> 
>> # read all lines of isildap.ini file
>> $lines = join("", <OLD>);
> 
>     my $lines = join "", <OLD>;
> 
> However, there's a better way to slurp in a whole file:
> 
>     open OLD, ...;
>     my $lines = do {
>         local $/;   # enable "slurp" mode
>         <OLD>;
>     };
> 
> The do() block returns its last evaluated statement which is "<OLD>".
> local() will give the variable $/ (it's a special variable and it's
> global) temporarily a new value. This new value only exists within the
> block. Upon leaving the block, it's previous value is restored. This
> mechanism is called dynamic scoping...it does not work with variables
> that had been declared with my() because those are lexicals. If you just
> use a variable without declaring it, you automatically get such a global
> and dynamically scoped variable. That's why you should use my(), unless
> you really need a dynamic variable.

And why is your 'slurp'-method exactly better? is it faster?
        

> Perl is not C.
> 
>> print NEW $lines;
>> print NEW "\n";
>> $newpattern = $&;
>> $newpattern =~ s/$oldcase/$newcase/g; print NEW $newpattern;
> 
> Here are two problems: you should not use the variable $& (same for $'
> and $`) unless you really need them. They will slow down every
> pattern-match in your script since now each pattern has to be made
> capturing. But you can avoid this global slowdown by making only
> selected patterns capturing:
> 
>     if ($lines =~ /(Case.*=.*$oldcase.*\{(.*?)\})/s) {
>         print "found match\n";
>         my $newpattern = $1;
>         $newpattern =~ s/$oldcase/$newcase/g; print NEW $newpattern;
>     }
>     }
> Another problem is even more serious: you assume that the pattern match
> succeeded, but you shouldn't. Whenever you use variables such as $&, $',
> $`, $1, $2, ..., make sure that the previous match did in fact succeed.
> Otherwise you end up having garbage in this variables. Perl does not
> reset them for each pattern match, that's why you have to wrap their
> usage as shown above.

ok, I rewrote the whole section, because it didn't work to match what i
wanted with regular expressions. Or do you know if it is possible to match
the following string with a reasonable simple regexp?

Case = SOME_CASE {

   subcase1 = {.....}
   ....	
   subcase2 = {......}

)

The whole block should be matched, but how do I tell the regexp not to
match the inner brackets?


> As for in-place editing of files, there's a useful idiom that is derived
> from a typical one-liner technique:
> 
>     # put all the files you want to edit
>     # into @ARGV
>     local @ARGV = qw( file1 file2 file3 ); local $^I   = '';   # it it
>     is defined, in-place edit is done while ($_ = <>) {
>         $_ =~ s/old/new/g;
>         print $_;
>     }
>     }
> $^I is the value of the -i switch (see 'perldoc perlrun'). <> reads one
> after the other each file in @ARGV. The current record (=line in this
> case) in the file is replaced with what you print. Note that you can do
> away with the $_ altogether:
> 
>     while (<>) {
>         s/old/new/g;
>         print;
>     }
>     }
> The limitation is that this is not going to work under Windows. I am not
> sure, but you can set $^I to a true value ('.bak') for instance. In this
> case, a backup of the original files is created with the suffix .bak.
> This might even work on Windows.
> 

ok, thanks, I found this tip also in the camel-perl-book. Really, really
simple i must say... :-)

Thanks again for your help

Matthias


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

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


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