[31388] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 2640 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Mon Oct 19 14:25:13 2009

Date: Mon, 19 Oct 2009 11:25:00 -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           Mon, 19 Oct 2009     Volume: 11 Number: 2640

Today's topics:
    Re: How would I do this in perl? <ben@morrow.me.uk>
    Re: How would I do this in perl? <jimsgibson@gmail.com>
    Re: How would I do this in perl? sln@netherlands.com
    Re: How would I do this in perl? sharma__r@hotmail.com
    Re: How would I do this in perl? <rvtol+usenet@xs4all.nl>
    Re: How would I do this in perl? <cartercc@gmail.com>
    Re: How would I do this in perl? <ben@morrow.me.uk>
    Re: How would I do this in perl? sln@netherlands.com
    Re: How would I do this in perl? sln@netherlands.com
    Re: How would I do this in perl? <cartercc@gmail.com>
    Re: How would I do this in perl? <jurgenex@hotmail.com>
    Re: How would I do this in perl? <tadmc@seesig.invalid>
    Re: How would I do this in perl? <hjp-usenet2@hjp.at>
    Re: How would I do this in perl? sharma__r@hotmail.com
    Re: How would I do this in perl? sln@netherlands.com
    Re: How would I do this in perl? <nospam-abuse@ilyaz.org>
    Re: How would I do this in perl? <spamtrap@shermpendley.com>
    Re: How would I do this in perl? <cartercc@gmail.com>
    Re: How would I do this in perl? <cartercc@gmail.com>
    Re: How would I do this in perl? sharma__r@hotmail.com
    Re: How would I do this in perl? <spamtrap@shermpendley.com>
    Re: How would I do this in perl? <tadmc@seesig.invalid>
    Re: How would I do this in perl? <ben@morrow.me.uk>
    Re: How would I do this in perl? <jurgenex@hotmail.com>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Wed, 14 Oct 2009 23:05:53 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: How would I do this in perl?
Message-Id: <1juhq6-9re.ln1@osiris.mauzo.dyndns.org>


Quoth laredotornado <laredotornado@zipmail.com>:
> 
> Thanks for this response.  Unfortunately, I get
> 
> Can't locate File/Slurp.pm in @INC (@INC contains: /opt/local/lib/
> perl5/5.8.8/darwin-2level /opt/local/lib/perl5/5.8.8 /opt/local/lib/
> perl5/site_perl/5.8.8/darwin-2level /opt/local/lib/perl5/site_perl/
> 5.8.8 /opt/local/lib/perl5/site_perl /opt/local/lib/perl5/vendor_perl/
> 5.8.8/darwin-2level /opt/local/lib/perl5/vendor_perl/5.8.8 /opt/local/
> lib/perl5/vendor_perl .) at test.pl line 1
> 
> Is there a quick way to download and install the slurp module?  I'm on
> a Mac OS X, using Perl 5.8.8.  Thanks, - Dave

perldoc -q install

Ben



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

Date: Wed, 14 Oct 2009 15:22:57 -0700
From: Jim Gibson <jimsgibson@gmail.com>
Subject: Re: How would I do this in perl?
Message-Id: <141020091522574581%jimsgibson@gmail.com>

In article
<9daad6a5-c771-49c7-89bf-42eaddd7c162@r24g2000prf.googlegroups.com>,
laredotornado <laredotornado@zipmail.com> wrote:

> On Oct 14, 3:16 pm, Ben Morrow <b...@morrow.me.uk> wrote:
> > Quoth laredotornado <laredotorn...@zipmail.com>:
> >

> >     use File::Slurp qw/slurp/;
> >
> >     my $template = slurp "template";
> >     my @n = slurp "numbers";
> >
> >     for (@n) {
> >         (my $out = $template) = s/X/$_/g;
> >         print $out;
> >     }
> >
> > Ben
> 
> Thanks for this response.  Unfortunately, I get
> 
> Can't locate File/Slurp.pm in @INC (@INC contains: /opt/local/lib/
> perl5/5.8.8/darwin-2level /opt/local/lib/perl5/5.8.8 /opt/local/lib/
> perl5/site_perl/5.8.8/darwin-2level /opt/local/lib/perl5/site_perl/
> 5.8.8 /opt/local/lib/perl5/site_perl /opt/local/lib/perl5/vendor_perl/
> 5.8.8/darwin-2level /opt/local/lib/perl5/vendor_perl/5.8.8 /opt/local/
> lib/perl5/vendor_perl .) at test.pl line 1
> 
> Is there a quick way to download and install the slurp module?  I'm on
> a Mac OS X, using Perl 5.8.8.  Thanks, - Dave

Try the following in the Terminal:

  sudo cpan
  install File::Slurp

You may have to answer some questions if this is the first time you
have run cpan.

You also may want to add after:

  my @n = slurp "numbers";

the following:

  chomp(@n);

to remove line ending characters from your numbers.

You might also want to read the advice in

  perldoc -q entire "How can I read an entire file all at once?"

-- 
Jim Gibson


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

Date: Wed, 14 Oct 2009 15:51:10 -0700
From: sln@netherlands.com
Subject: Re: How would I do this in perl?
Message-Id: <7clcd5hks65ng6iqjpf4cdcpo5f6sn6ali@4ax.com>

On Wed, 14 Oct 2009 14:37:38 -0700 (PDT), laredotornado <laredotornado@zipmail.com> wrote:

>On Oct 14, 3:16 pm, Ben Morrow <b...@morrow.me.uk> wrote:
>> Quoth laredotornado <laredotorn...@zipmail.com>:
>>
>>
>>
>>
>>
>> > I'm not so familiar with perl but it seems this is the kind of task it
>> > is suited for.  I have a file of numbers, one number per line.  Then I
>> > have a template file that contains ...
>>
>> >    public void testXMatchValid_UCASE() throws java.lang.Exception {
>> >            _testMatchUpperCase(X);
>> >    }
>>
>> >    public void testXMatchValid_lcase() throws java.lang.Exception {
>> >            _testMatchLowerCase(X);
>> >    }
>>
>> > I want the final file to have each number replace the "X" in the
>> > template file and the template would repeat for the number of lines in
>> > the numbers file.  So if the numbers file contained
>>
>> (untested)
>>
>>     use File::Slurp qw/slurp/;
>>
>>     my $template = slurp "template";
>>     my @n = slurp "numbers";
>>
>>     for (@n) {
>>         (my $out = $template) = s/X/$_/g;
>>         print $out;
>>     }
>>
>> Ben
>
>Thanks for this response.  Unfortunately, I get
>
>Can't locate File/Slurp.pm in @INC (@INC contains: /opt/local/lib/
>perl5/5.8.8/darwin-2level /opt/local/lib/perl5/5.8.8 /opt/local/lib/
>perl5/site_perl/5.8.8/darwin-2level /opt/local/lib/perl5/site_perl/
>5.8.8 /opt/local/lib/perl5/site_perl /opt/local/lib/perl5/vendor_perl/
>5.8.8/darwin-2level /opt/local/lib/perl5/vendor_perl/5.8.8 /opt/local/
>lib/perl5/vendor_perl .) at test.pl line 1
>
>Is there a quick way to download and install the slurp module?  I'm on
>a Mac OS X, using Perl 5.8.8.  Thanks, - Dave

But then again before you install the world, slurp is not
even an issue (nor needed) for your problem description.

-sln


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

Date: Wed, 14 Oct 2009 21:34:40 -0700 (PDT)
From: sharma__r@hotmail.com
Subject: Re: How would I do this in perl?
Message-Id: <2991cc95-5234-4877-9750-603233ef81ff@x5g2000prf.googlegroups.com>

On Oct 15, 1:31=A0am, laredotornado <laredotorn...@zipmail.com> wrote:
> Hi,
>
> I'm not so familiar with perl but it seems this is the kind of task it
> is suited for. =A0I have a file of numbers, one number per line. =A0Then =
I
> have a template file that contains ...
>
> =A0 =A0 =A0 =A0 public void testXMatchValid_UCASE() throws java.lang.Exce=
ption {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 _testMatchUpperCase(X);
> =A0 =A0 =A0 =A0 }
>
> =A0 =A0 =A0 =A0 public void testXMatchValid_lcase() throws java.lang.Exce=
ption {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 _testMatchLowerCase(X);
> =A0 =A0 =A0 =A0 }
>
> I want the final file to have each number replace the "X" in the
> template file and the template would repeat for the number of lines in
> the numbers file. =A0So if the numbers file contained
>
> 10
> 20
>
> the resulting output file would contain
>
> =A0 =A0 =A0 =A0 public void test10MatchValid_UCASE() throws java.lang.Exc=
eption {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 _testMatchUpperCase(10);
> =A0 =A0 =A0 =A0 }
>
> =A0 =A0 =A0 =A0 public void test10MatchValid_lcase() throws java.lang.Exc=
eption {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 _testMatchLowerCase(10);
> =A0 =A0 =A0 =A0 }
>
> =A0 =A0 =A0 =A0 public void test20MatchValid_UCASE() throws java.lang.Exc=
eption {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 _testMatchUpperCase(20);
> =A0 =A0 =A0 =A0 }
>
> =A0 =A0 =A0 =A0 public void test20MatchValid_lcase() throws java.lang.Exc=
eption {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 _testMatchLowerCase(20);
> =A0 =A0 =A0 =A0 }
>
> HOw would I pull this off using perl? =A0Thanks, - Dave

(untested)

perl -wlne '
  do{ $temp .=3D qq{\n} .$_; next; } if $ARGV eq q{template};

  ($temp_copy =3D $temp) =3D~ s/X/$_/;

  print $temp_copy;
' template_file nums_file


Note: The ordering of the file arguments to perl is essential.


--Rakesh


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

Date: Thu, 15 Oct 2009 10:46:40 +0200
From: "Dr.Ruud" <rvtol+usenet@xs4all.nl>
Subject: Re: How would I do this in perl?
Message-Id: <4ad6e171$0$83235$e4fe514c@news.xs4all.nl>

laredotornado wrote:

> Is there a quick way to download and install the slurp module?  I'm on
> a Mac OS X, using Perl 5.8.8.

I use ports: http://darwinports.com/

-- 
Ruud


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

Date: Thu, 15 Oct 2009 07:42:30 -0700 (PDT)
From: ccc31807 <cartercc@gmail.com>
Subject: Re: How would I do this in perl?
Message-Id: <de88ea19-681c-450d-a2da-18e9545beba9@k17g2000yqb.googlegroups.com>

On Oct 14, 4:31=A0pm, laredotornado <laredotorn...@zipmail.com> wrote:
> I have a file of numbers, one number per line. =A0Then I
> have a template file that contains ...
>
> =A0 =A0 =A0 =A0 public void testXMatchValid_UCASE() throws java.lang.Exce=
ption {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 _testMatchUpperCase(X);
> =A0 =A0 =A0 =A0 }
>
> =A0 =A0 =A0 =A0 public void testXMatchValid_lcase() throws java.lang.Exce=
ption {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 _testMatchLowerCase(X);
> =A0 =A0 =A0 =A0 }
>
> I want the final file to have each number replace the "X" in the
> template file and the template would repeat for the number of lines in
> the numbers file. =A0So if the numbers file contained
>
> 10
> 20

This is much more verbose than the other suggestions, but maybe easier
to understand. I have tested the code, and it produces the correct
output.

use strict;
use warnings;
#open number file for reading
open NUMBERS, '<', 'numbers.dat';
#open output file for appending
open OUTFILE, '>>', 'output.java';
#iterate through number file
while (<NUMBERS>)
{
  #check for digits
  next unless /\d/;
  #remove the newline
  chomp;
  #save each number for later use
  my $number =3D $_;
  #open template file for reading
  open TEMPLATE, '<', 'template.java';
  #iterate through template file
  while(<TEMPLATE>)
  {
    #replace X with $number
    $_ =3D~ s/X/$number/;
    # print to outfile
    print OUTFILE $_;
  }
  close TEMPLATE;
}
close NUMBERS;
close OUTFILE;
exit(0);


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

Date: Thu, 15 Oct 2009 15:55:37 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: How would I do this in perl?
Message-Id: <9opjq6-g1m.ln1@osiris.mauzo.dyndns.org>


Quoth ccc31807 <cartercc@gmail.com>:
> 
> This is much more verbose than the other suggestions, but maybe easier
> to understand. I have tested the code, and it produces the correct
> output.
> 
> use strict;
> use warnings;
> #open number file for reading
> open NUMBERS, '<', 'numbers.dat';

Don't use bareword filehandles.
Check the return value of open.

    open my $NUMBERS, '<', 'numbers.dat'
        or die "can't read 'numbers.dat': $!";

> #open output file for appending
> open OUTFILE, '>>', 'output.java';

ditto

> #iterate through number file
> while (<NUMBERS>)
> {
>   #check for digits
>   next unless /\d/;
>   #remove the newline
>   chomp;
>   #save each number for later use
>   my $number = $_;
>   #open template file for reading
>   open TEMPLATE, '<', 'template.java';

You are re-opening the template for every number. This is a bad idea:
its contents aren't going to change, so just read them once and remember
them.

>   #iterate through template file
>   while(<TEMPLATE>)

There's no point iterating line-by-line if you're doing a replacement on
the whole file (unless you expect your files to exceed memory). It's
much clearer (as well as probably more efficient) to read the whole file
in and do and s/// over the whole thing.

>   {
>     #replace X with $number
>     $_ =~ s/X/$number/;

'$_ =~' is redundant.
You need a /g there.

Ben



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

Date: Thu, 15 Oct 2009 09:19:14 -0700
From: sln@netherlands.com
Subject: Re: How would I do this in perl?
Message-Id: <4khed5dpdpom60548n99u8bugfi236qgri@4ax.com>

On Wed, 14 Oct 2009 13:31:23 -0700 (PDT), laredotornado <laredotornado@zipmail.com> wrote:

>Hi,
>
>I'm not so familiar with perl but it seems this is the kind of task it
>is suited for.  I have a file of numbers, one number per line.  Then I
>have a template file that contains ...
>
>	public void testXMatchValid_UCASE() throws java.lang.Exception {
>		_testMatchUpperCase(X);
>	}
>
>	public void testXMatchValid_lcase() throws java.lang.Exception {
>		_testMatchLowerCase(X);
>	}
>
>I want the final file to have each number replace the "X" in the
>template file and the template would repeat for the number of lines in
>the numbers file.  So if the numbers file contained
>
>10
>20
>
>the resulting output file would contain
>
>	public void test10MatchValid_UCASE() throws java.lang.Exception {
>		_testMatchUpperCase(10);
>	}
>
>	public void test10MatchValid_lcase() throws java.lang.Exception {
>		_testMatchLowerCase(10);
>	}
>
>	public void test20MatchValid_UCASE() throws java.lang.Exception {
>		_testMatchUpperCase(20);
>	}
>
>	public void test20MatchValid_lcase() throws java.lang.Exception {
>		_testMatchLowerCase(20);
>	}
>
>
>HOw would I pull this off using perl?  Thanks, - Dave

Just out of curiosity, a couple of questions.
Why would you define totally static wrapper function's, distinct
in name for each number, when they all call the same function?
And how did you plan on calling these?

test10MatchValid_UCASE();
test20MatchValid_UCASE();
test30MatchValid_UCASE();
 ...

Why not just call a single function from a loop with 
variable data?

  int num[] = {10,20, ...};  // or num array can be generated
                             // or generated in the for(,,)
  for (int i = 0; i < (sizeof(num)/int); i++) {
	testMatchValid_UCASE(num[i]);  // what are we testing, no exceptions?
	testMatchValid_lcase(num[i]);
  }

I think you might be just curious about Perl's ability to do things
well, like mail-merge (macro's ?).

-sln


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

Date: Thu, 15 Oct 2009 09:23:55 -0700
From: sln@netherlands.com
Subject: Re: How would I do this in perl?
Message-Id: <o1jed5lu6mtj4ji50bftksk3dlu9d9fnc5@4ax.com>

On Thu, 15 Oct 2009 09:19:14 -0700, sln@netherlands.com wrote:

>On Wed, 14 Oct 2009 13:31:23 -0700 (PDT), laredotornado <laredotornado@zipmail.com> wrote:
>
>Why not just call a single function from a loop with 
>variable data?
>
>  int num[] = {10,20, ...};  // or num array can be generated
>                             // or generated in the for(,,)
>  for (int i = 0; i < (sizeof(num)/int); i++) {
                          ^^^^^^^^^^^
                     sizeof(num)/sizeof(int)

Its been a while.
-sln



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

Date: Thu, 15 Oct 2009 10:56:01 -0700 (PDT)
From: ccc31807 <cartercc@gmail.com>
Subject: Re: How would I do this in perl?
Message-Id: <c1142c0d-2146-4f79-92f0-9992e1610c15@g31g2000yqc.googlegroups.com>

On Oct 15, 10:55=A0am, Ben Morrow <b...@morrow.me.uk> wrote:
> Don't use bareword filehandles.

My Perl documentation (5.8) demonstrates the syntax I used. Is the
documentation wrong? What is the rationale for avoiding bareword
filehandles?

> Check the return value of open.

Yeah, yeah, we go through this almost every time.


> You are re-opening the template for every number. This is a bad idea:
> its contents aren't going to change, so just read them once and remember
> them.

My purpose was to demonstrate iterating through a template file. How
do you iterate through a template file when you read it into memory?
I'm asking this because I don't understand your logic in doing this. I
agree that opening and closing the same file many times seems like a
stupid idea.

> There's no point iterating line-by-line if you're doing a replacement on
> the whole file (unless you expect your files to exceed memory). It's
> much clearer (as well as probably more efficient) to read the whole file
> in and do and s/// over the whole thing.

Again, I wanted something clear rather than concise. Since the
template file has to be written many time, I guess I just don't see
it.

> '$_ =3D~' is redundant.

Yes, but it makes clear that $_ is being changed each time, maximizing
verbosity for clarity.

> You need a /g there.

Not if there is only one change per line, which is how the template is
specified.

Please note, terse code can be very difficult to understand, and Perl
allows very terse shortcuts. The OP said that he didn't know Perl
well. I have gotten into a bad habit myself of using some of these
shortcuts, and sometimes am reminded that verbosity is better. A
couple of days ago, I did this:
sub afunction
{ my $var =3D shift;
 ... }

and a colleague wanted to know what 'shift' meant. I was at fault for
using the shortcut, and he wasn't at fault by not having learned the
usage of 'shift'.

CC.


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

Date: Thu, 15 Oct 2009 11:35:35 -0700
From: Jürgen Exner <jurgenex@hotmail.com>
Subject: Re: How would I do this in perl?
Message-Id: <6nqed51bqirr57t5vov6ukgmsf0nbdkfbv@4ax.com>

ccc31807 <cartercc@gmail.com> wrote:
>On Oct 15, 10:55 am, Ben Morrow <b...@morrow.me.uk> wrote:
>> You are re-opening the template for every number. This is a bad idea:
>> its contents aren't going to change, so just read them once and remember
>> them.
>
>My purpose was to demonstrate iterating through a template file. How
>do you iterate through a template file when you read it into memory?

You want iterate over the _content_ of the file, not the file. Therefore
it is irrelevant if that content is on the HD or in memory, you can
iterate over it either way.

jue


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

Date: Thu, 15 Oct 2009 14:54:45 -0500
From: Tad J McClellan <tadmc@seesig.invalid>
Subject: Re: How would I do this in perl?
Message-Id: <slrnhdeujn.tts.tadmc@tadmc30.sbcglobal.net>

ccc31807 <cartercc@gmail.com> wrote:
> On Oct 15, 10:55 am, Ben Morrow <b...@morrow.me.uk> wrote:
>> Don't use bareword filehandles.
>
> My Perl documentation (5.8) demonstrates the syntax I used. 


The documentation also shows code with no warning or strict enabled.

Just because you _can_ do something does not mean that you _should_ do it.


> Is the
> documentation wrong? 


No.


> What is the rationale for avoiding bareword
> filehandles?


Bareword filehandles are global, globals are bad.

See the "Indirect Filehandles" section in:

    perldoc perlopentut


>> Check the return value of open.
>
> Yeah, yeah, we go through this almost every time.


Then please include it when you post code so that you do not
spawn yet another time where it must be pointed out.


>> You are re-opening the template for every number. This is a bad idea:
>> its contents aren't going to change, so just read them once and remember
>> them.
>
> My purpose was to demonstrate iterating through a template file. 


But the problem does not require that iterating (by line).


> How
> do you iterate through a template file when you read it into memory?


    foreach my $line ( $template =~ /.*\n/g ) {
        # do something with $line
    }


-- 
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"


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

Date: Thu, 15 Oct 2009 21:57:26 +0200
From: "Peter J. Holzer" <hjp-usenet2@hjp.at>
Subject: Re: How would I do this in perl?
Message-Id: <slrnhdevl7.hb1.hjp-usenet2@hrunkner.hjp.at>

On 2009-10-15 17:56, ccc31807 <cartercc@gmail.com> wrote:
> On Oct 15, 10:55 am, Ben Morrow <b...@morrow.me.uk> wrote:
>> Don't use bareword filehandles.
>
> My Perl documentation (5.8) demonstrates the syntax I used.

So does 5.10 and so will 5.12.

> Is the
> documentation wrong?

No. Bareword filehandles have existed since the beginning of Perl and
they will probably exist as long as Perl 5.x.

> What is the rationale for avoiding bareword filehandles?

They are global. Global variables in general are a bad idea. Global
variables which you don't have to declare are an even worse idea.
The risk that you accidentally use the same file handle in two
independent subroutines is quite big. Happened to me a few times and it
always took me a long time to find the bug. Lexical filehandles
(introduced in Perl 5.6, IIRC) are a lot safer. They are also normal
scalars, so you can pass them around as arguments like any other scalar.

	hp



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

Date: Thu, 15 Oct 2009 13:45:35 -0700 (PDT)
From: sharma__r@hotmail.com
Subject: Re: How would I do this in perl?
Message-Id: <52c17311-1e21-47ce-993c-997c728ef52f@v37g2000prg.googlegroups.com>

On Oct 15, 10:56=A0pm, ccc31807 <carte...@gmail.com> wrote:
> On Oct 15, 10:55=A0am, Ben Morrow <b...@morrow.me.uk> wrote:
>
> > Don't use bareword filehandles.
>
> My Perl documentation (5.8) demonstrates the syntax I used. Is the
> documentation wrong? What is the rationale for avoiding bareword
> filehandles?
>
> > Check the return value of open.
>
> Yeah, yeah, we go through this almost every time.
>
> > You are re-opening the template for every number. This is a bad idea:
> > its contents aren't going to change, so just read them once and remembe=
r
> > them.
>
> My purpose was to demonstrate iterating through a template file. How
> do you iterate through a template file when you read it into memory?
> I'm asking this because I don't understand your logic in doing this. I
> agree that opening and closing the same file many times seems like a
> stupid idea.
>
> > There's no point iterating line-by-line if you're doing a replacement o=
n
> > the whole file (unless you expect your files to exceed memory). It's
> > much clearer (as well as probably more efficient) to read the whole fil=
e
> > in and do and s/// over the whole thing.
>
> Again, I wanted something clear rather than concise. Since the
> template file has to be written many time, I guess I just don't see
> it.
>
> > '$_ =3D~' is redundant.
>
> Yes, but it makes clear that $_ is being changed each time, maximizing
> verbosity for clarity.
>
> > You need a /g there.
>
> Not if there is only one change per line, which is how the template is
> specified.
>
> Please note, terse code can be very difficult to understand, and Perl
> allows very terse shortcuts. The OP said that he didn't know Perl
> well. I have gotten into a bad habit myself of using some of these
> shortcuts, and sometimes am reminded that verbosity is better. A
> couple of days ago, I did this:
> sub afunction
> { my $var =3D shift;
> ... }
>
> and a colleague wanted to know what 'shift' meant. I was at fault for
> using the shortcut, and he wasn't at fault by not having learned the
> usage of 'shift'.
>
> CC.


Another thing that I want to point out is that you are using the $_
variable
in the two 'while' loops. Since your focus is on clarity, then this
actually
has a reverse effect!

####################### alternate  ################################
#!/usr/local/bin/perl
use 5.006; # or later, to be able to use the 3-arg form of open with
lexical filenandles
use strict;
use warnings;

local $\ =3D qq{\n}; # auto-append newlines after every print

### store the template into a scalar
my $template =3D 'template.java';
open my $template_FH, "<", $template
   or die "Could not open the java template [$template] for reading:
$!";
my $code =3D do {
   local $/ =3D undef;
   <$template_FH>;
};
close $template_FH
   or die "Could not close the java template [$template] after
reading: $!";
chomp $code;

### loop over the numbers
my $numbers =3D 'numbers.dat';
open my $numbers_FH, "<", $numbers
   or die "Could not open the the numbers file [$numbers] for reading:
$!";

my $java_result =3D 'output.java';
warn "The file [$java_result] is about to be clobbered." if -e
$java_result;
open my $out_FH, ">", $java_result
   or die "Could not open the file [$java_result] for writing: $!";

NUMBER:
while (defined(my $number =3D <$numbers_FH>)) {
   # invalid line if any non-digit found
   next NUMBER if $number =3D~ m/\D/;

   chomp $number;

   (my $template_copy =3D $code) =3D~ s/X/$number/g;

   print {$out_FH} $template_copy;
}

close $numbers_FH
   or die "Could not close the numbers file [$numbers] after reading:
$!";

close $out_FH
   or die "Could not close the file [$java_result] after writing: $!";

__END__




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

Date: Thu, 15 Oct 2009 15:08:53 -0700
From: sln@netherlands.com
Subject: Re: How would I do this in perl?
Message-Id: <g95fd597sqmq9u881v9gfoeiu43g8blu41@4ax.com>

On Thu, 15 Oct 2009 13:45:35 -0700 (PDT), sharma__r@hotmail.com wrote:

>On Oct 15, 10:56 pm, ccc31807 <carte...@gmail.com> wrote:
>> On Oct 15, 10:55 am, Ben Morrow <b...@morrow.me.uk> wrote:
>>
>> > Don't use bareword filehandles.
>>
>> My Perl documentation (5.8) demonstrates the syntax I used. Is the
>> documentation wrong? What is the rationale for avoiding bareword
>> filehandles?
>>
>> > Check the return value of open.
>>
>> Yeah, yeah, we go through this almost every time.
>>
>> > You are re-opening the template for every number. This is a bad idea:
>> > its contents aren't going to change, so just read them once and remember
>> > them.
>>
>> My purpose was to demonstrate iterating through a template file. How
>> do you iterate through a template file when you read it into memory?
>> I'm asking this because I don't understand your logic in doing this. I
>> agree that opening and closing the same file many times seems like a
>> stupid idea.
>>
>> > There's no point iterating line-by-line if you're doing a replacement on
>> > the whole file (unless you expect your files to exceed memory). It's
>> > much clearer (as well as probably more efficient) to read the whole file
>> > in and do and s/// over the whole thing.
>>
>> Again, I wanted something clear rather than concise. Since the
>> template file has to be written many time, I guess I just don't see
>> it.
>>
>> > '$_ =~' is redundant.
>>
>> Yes, but it makes clear that $_ is being changed each time, maximizing
>> verbosity for clarity.
>>
>> > You need a /g there.
>>
>> Not if there is only one change per line, which is how the template is
>> specified.
>>
>> Please note, terse code can be very difficult to understand, and Perl
>> allows very terse shortcuts. The OP said that he didn't know Perl
>> well. I have gotten into a bad habit myself of using some of these
>> shortcuts, and sometimes am reminded that verbosity is better. A
>> couple of days ago, I did this:
>> sub afunction
>> { my $var = shift;
>> ... }
>>
>> and a colleague wanted to know what 'shift' meant. I was at fault for
>> using the shortcut, and he wasn't at fault by not having learned the
>> usage of 'shift'.
>>
>> CC.
>
>
>Another thing that I want to point out is that you are using the $_
>variable
>in the two 'while' loops. Since your focus is on clarity, then this
>actually
>has a reverse effect!
>
>####################### alternate  ################################
>#!/usr/local/bin/perl
>use 5.006; # or later, to be able to use the 3-arg form of open with
>lexical filenandles
>use strict;
>use warnings;
>
>local $\ = qq{\n}; # auto-append newlines after every print
>
>### store the template into a scalar
>my $template = 'template.java';
>open my $template_FH, "<", $template
>   or die "Could not open the java template [$template] for reading:
>$!";
>my $code = do {
>   local $/ = undef;
>   <$template_FH>;
>};
>close $template_FH
>   or die "Could not close the java template [$template] after
>reading: $!";
>chomp $code;
>
>### loop over the numbers
>my $numbers = 'numbers.dat';
>open my $numbers_FH, "<", $numbers
>   or die "Could not open the the numbers file [$numbers] for reading:
>$!";
>
>my $java_result = 'output.java';
>warn "The file [$java_result] is about to be clobbered." if -e
>$java_result;
      
-   Why 'warn' then clobber it anyway?

>open my $out_FH, ">", $java_result
>   or die "Could not open the file [$java_result] for writing: $!";
>
>NUMBER:
>while (defined(my $number = <$numbers_FH>)) {
>   # invalid line if any non-digit found
>   next NUMBER if $number =~ m/\D/;
                              ^^^^^
-    This will always fail unless line equals "\d+"
     Either
         while (defined(my $number = <DATA>)) {
              $number =~ s/^\s*(\d+)\s*$/$1/ or next NUMBER;
     Or
         while (<DATA>) {
              my ($number) = /^\s*(\d+)\s*$/ or next;
>
>   chomp $number;
>
>   (my $template_copy = $code) =~ s/X/$number/g;

-   I guess loading a copy of the template file into
    memory makes this faster than reading a file line
    by line, rewind, repeat .., but not by much given
    file cache.

    Of course, this is not the fastest method. You are
    actually copying the file data over and over again,
    then doing regex with substitution (more overhead)
    over and over again. These duplicate action's add
    signifcantly to the overhead.

    The fastest method, if actual speed is a factor,
    is to read the template into memory, index the
    substitution points into an array one time,
    then write segments to the output file, directly,
    using substr. Or instead of indexing, just creating
    an array of segments (strings).

>
>   print {$out_FH} $template_copy;
>}
>
>close $numbers_FH
>   or die "Could not close the numbers file [$numbers] after reading:
>$!";
>
>close $out_FH
>   or die "Could not close the file [$java_result] after writing: $!";
>
>__END__
>

-sln


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

Date: Thu, 15 Oct 2009 22:50:21 +0000 (UTC)
From: Ilya Zakharevich <nospam-abuse@ilyaz.org>
Subject: Re: How would I do this in perl?
Message-Id: <slrnhdf9pd.qpf.nospam-abuse@chorin.math.berkeley.edu>

On 2009-10-15, Ben Morrow <ben@morrow.me.uk> wrote:
>> open NUMBERS, '<', 'numbers.dat';
>
> Don't use bareword filehandles.

To the contrary: unless in a 1-liner, one should carefully consider
using bareword filehandles.

  [If code is supposed to be reused, you rarely know on which version
   of Perl it is going to be reused.]

Ilya


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

Date: Fri, 16 Oct 2009 10:20:14 -0400
From: Sherm Pendley <spamtrap@shermpendley.com>
Subject: Re: How would I do this in perl?
Message-Id: <m2vdifpgip.fsf@shermpendley.com>

ccc31807 <cartercc@gmail.com> writes:

> On Oct 15, 10:55 am, Ben Morrow <b...@morrow.me.uk> wrote:
>> Don't use bareword filehandles.
>
> My Perl documentation (5.8) demonstrates the syntax I used.

So? The fact that they're allowed for compatibility's sake doesn't imply
that using them in new code is a good idea. Lexical filehandles were
intoduced in 5.6, and they have a number of advantages.

> What is the rationale for avoiding bareword filehandles?

For one thing, they're globals, with all the problems that implies. A
lexical file handle is limited in scope, and automagically closed when
it goes out of scope.

>> Check the return value of open.
>
> Yeah, yeah, we go through this almost every time.

Then why haven't you learned it yet? How many repetitions will it take
until you understand the value of error-checking?

sherm--


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

Date: Fri, 16 Oct 2009 10:39:36 -0700 (PDT)
From: ccc31807 <cartercc@gmail.com>
Subject: Re: How would I do this in perl?
Message-Id: <36c262d0-9144-4bf6-89f5-fe3be3d4f113@k33g2000yqa.googlegroups.com>

On Oct 15, 3:57=A0pm, "Peter J. Holzer" <hjp-usen...@hjp.at> wrote:
> > What is the rationale for avoiding bareword filehandles?
>
> They are global. Global variables in general are a bad idea. Global
> variables which you don't have to declare are an even worse idea.
> The risk that you accidentally use the same file handle in two
> independent subroutines is quite big. Happened to me a few times and it
> always took me a long time to find the bug. Lexical filehandles
> (introduced in Perl 5.6, IIRC) are a lot safer. They are also normal
> scalars, so you can pass them around as arguments like any other scalar.

Good. This makes sense.

CC.


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

Date: Fri, 16 Oct 2009 10:49:56 -0700 (PDT)
From: ccc31807 <cartercc@gmail.com>
Subject: Re: How would I do this in perl?
Message-Id: <f52dd878-1cbb-4d12-87f1-987ff2e84f1a@a32g2000yqm.googlegroups.com>

On Oct 16, 10:20=A0am, Sherm Pendley <spamt...@shermpendley.com> wrote:
> >> Check the return value of open.
>
> > Yeah, yeah, we go through this almost every time.
>
> Then why haven't you learned it yet? How many repetitions will it take
> until you understand the value of error-checking?

My job requires a lot of data manipulation. I write a lot of short
scripts to munge data files on a one time basis. open() and close()
never fail (unless I already have the data file open, in which case
the problem is obvious.) In this very specific environment, I don't
really need the error checking and can't justify the time spent typing
the extra keystrokes.

I don't doubt the value of error checking. That's not the point. The
point is that (as Emerson said) a foolish consistency is the hobgoblin
of small minds -- IOW, why go to the extra effort of this kind of
error checking when it's not needed in a particular situation,
regardless of its value in general? Just because a practice is
considered best generally doesn't necessarily that it should always be
adhered to in all circumstances. I wear my seatbelt when driving, but
I don't fasten it when I move the car to wash it.

CC


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

Date: Fri, 16 Oct 2009 11:03:37 -0700 (PDT)
From: sharma__r@hotmail.com
Subject: Re: How would I do this in perl?
Message-Id: <ead7fc5c-da82-47e9-9478-670359d292d1@13g2000prl.googlegroups.com>

On Oct 16, 3:08=A0am, s...@netherlands.com wrote:

> >my $java_result =3D 'output.java';
> >warn "The file [$java_result] is about to be clobbered." if -e
> >$java_result;
>
> - =A0 Why 'warn' then clobber it anyway?

Guess you're right. I couldn't think up of anything better ;-)



> >NUMBER:
> >while (defined(my $number =3D <$numbers_FH>)) {
> > =A0 # invalid line if any non-digit found
> > =A0 next NUMBER if $number =3D~ m/\D/;
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 ^^^^^
> - =A0 =A0This will always fail unless line equals "\d+"
> =A0 =A0 =A0Either
> =A0 =A0 =A0 =A0 =A0while (defined(my $number =3D <DATA>)) {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 $number =3D~ s/^\s*(\d+)\s*$/$1/ or next NUMB=
ER;
> =A0 =A0 =A0Or
> =A0 =A0 =A0 =A0 =A0while (<DATA>) {
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 my ($number) =3D /^\s*(\d+)\s*$/ or next;

You're observation is right on the mark. Actually it'll always fail
since the
matching happens before chomping, so the \n will match the \D

Actually the solution is very simple!
               next NUMBER if $number =3D~ m/\D./xms



> > =A0 (my $template_copy =3D $code) =3D~ s/X/$number/g;
> - =A0 I guess loading a copy of the template file into
> =A0 =A0 memory makes this faster than reading a file line
> =A0 =A0 by line, rewind, repeat .., but not by much given
> =A0 =A0 file cache.
>
> =A0 =A0 Of course, this is not the fastest method. You are
> =A0 =A0 actually copying the file data over and over again,
> =A0 =A0 then doing regex with substitution (more overhead)
> =A0 =A0 over and over again. These duplicate action's add
> =A0 =A0 signifcantly to the overhead.
>
> =A0 =A0 The fastest method, if actual speed is a factor,
> =A0 =A0 is to read the template into memory, index the
> =A0 =A0 substitution points into an array one time,
> =A0 =A0 then write segments to the output file, directly,
> =A0 =A0 using substr. Or instead of indexing, just creating
> =A0 =A0 an array of segments (strings).
>

Err :-\ speed was not on my mind in the code that I presented. I was
presenting it more
from a clarity standpoint.

Your speed optimization looks very interesting, but please show the
perl implementation.

--Rakesh


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

Date: Fri, 16 Oct 2009 14:44:17 -0400
From: Sherm Pendley <spamtrap@shermpendley.com>
Subject: Re: How would I do this in perl?
Message-Id: <m2zl7ruqke.fsf@shermpendley.com>

ccc31807 <cartercc@gmail.com> writes:

> I don't doubt the value of error checking. That's not the point. The
> point is that (as Emerson said) a foolish consistency is the hobgoblin
> of small minds

The caveat being "foolish." Not all consistency is foolish.

> -- IOW, why go to the extra effort of this kind of
> error checking when it's not needed in a particular situation,

For one thing, it's a trivial amount of effort. In this thread alone,
you've put more work into justifying the absence of error checking than
it would have taken you to simply include it to begin with.

For another, error-checking code is like a condom or a gun - it's better
to have one and not need it, than need one and not have it.

sherm--


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

Date: Fri, 16 Oct 2009 14:44:30 -0500
From: Tad J McClellan <tadmc@seesig.invalid>
Subject: Re: How would I do this in perl?
Message-Id: <slrnhdhicd.ngb.tadmc@tadmc30.sbcglobal.net>

ccc31807 <cartercc@gmail.com> wrote:
> On Oct 16, 10:20 am, Sherm Pendley <spamt...@shermpendley.com> wrote:
>> >> Check the return value of open.
>>
>> > Yeah, yeah, we go through this almost every time.
>>
>> Then why haven't you learned it yet? How many repetitions will it take
>> until you understand the value of error-checking?
>
> My job requires a lot of data manipulation. I write a lot of short
> scripts to munge data files on a one time basis. open() and close()
> never fail


You have never mistyped a filename?

You are so awesome!


> I don't doubt the value of error checking. That's not the point. The
> point is that (as Emerson said) a foolish consistency is the hobgoblin
> of small minds -- IOW, why go to the extra effort of this kind of
> error checking when it's not needed in a particular situation,


checking the return value from open() is needed in every situation,
because it can fail in any situation.

I have open() with return value checking saved in an edit buffer, so
I won't be tempted to spew bad code upon the world.


> Just because a practice is
> considered best generally doesn't necessarily that it should always be
> adhered to in all circumstances. I wear my seatbelt when driving, but
> I don't fasten it when I move the car to wash it.


Code posted here is likely to be copied by posters days, weeks or
years from now.

Seeding failure is a disservice to our community.

If you cannot be troubled to post Good Code, then don't post code,
Perl programmers will be the better for it.


-- 
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"


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

Date: Sun, 18 Oct 2009 18:23:43 +0100
From: Ben Morrow <ben@morrow.me.uk>
Subject: Re: How would I do this in perl?
Message-Id: <vhvrq6-54c1.ln1@osiris.mauzo.dyndns.org>


Quoth Ilya Zakharevich <nospam-abuse@ilyaz.org>:
> On 2009-10-15, Ben Morrow <ben@morrow.me.uk> wrote:
> >> open NUMBERS, '<', 'numbers.dat';
> >
> > Don't use bareword filehandles.
> 
> To the contrary: unless in a 1-liner, one should carefully consider
> using bareword filehandles.
> 
>   [If code is supposed to be reused, you rarely know on which version
>    of Perl it is going to be reused.]

*I* can generally be fairly certain my code won't be used on perls
before 5.6. For one thing, I almost always 'use warnings'.

Ben



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

Date: Sun, 18 Oct 2009 11:57:06 -0700
From: Jürgen Exner <jurgenex@hotmail.com>
Subject: Re: How would I do this in perl?
Message-Id: <bpomd5t21fu3ll0ksacmc1i5qhu284hggs@4ax.com>

Ilya Zakharevich <nospam-abuse@ilyaz.org> wrote:
>To the contrary: unless in a 1-liner, one should carefully consider
>using bareword filehandles.
>
>  [If code is supposed to be reused, you rarely know on which version
>   of Perl it is going to be reused.]

If the code needs to be backward compatible to before 5.6, then you have
much bigger problems to worry about than bareword filehandles.

jue


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

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:

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

Back issues are available via anonymous ftp from
ftp://cil-www.oce.orst.edu/pub/perl/old-digests. 

#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 V11 Issue 2640
***************************************


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