On Jul 22, Bob H said:

>I have a script that is *supposed* to search a file and make certain
>words that I have in an array uppercase. My brain is not grokking it.

You should not use tr/// to make strings uppercase.  Perl provides the
uc() function for that.

>Q1: What is wrong with my script (below)?

I'll point it out.

>Q2: Can I update a file in place?

Yes, using the $^I and @ARGV varaibles.

>Q3: How do I run multiple things against one file in one script?

Send multiple files as command-line args, and loop over the @ARGV array.

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

BRAVO! :)

># variables
>my $word = undef;

The '= undef' part is redundant.

># setup the words to uppercase
>my @words = qw/ Mary John Joe /;
>
>open FILE, ">> NEW1 "  or die "can't open FILE:  $!";
>
>while (<>) {
>     foreach $word (@words) {
>         $word = ~ tr /a-z/A-Z/;
>         print FILE;
>     }

A bunch of problems here.

1. you're print the same line to FILE X times, where X is the size of the
@words array
2. you're trying to modify the elements of @words, instead of $_
3. you've got a space in the middle of the =~ operator

This is quite funny, actually.  Because of that space, your code appears
to capitalize the entire string and print it three (in your example)
times.  Why?  Because

  $word = ~ tr/a-z/A-Z/;

is like

  $word = ~($_ =~ tr/a-z/A-Z/);

>}
>
># close the file
>close (FILE);

Here is a multi-file in-place working solution:

  #!/usr/bin/perl

  use strict;
  use warnings;

  $^I = ".bak";  # keep a backup of the files as xxx.bak
  my @words = qw( make these caps );
  my $rx = join "|", map quotemeta, @words;

  # $rx is 'make|these|caps'

  # perl is magic
  while (<>) {
    s/\b($rx)\b/\U$1/ig;  # "\U$1" is like uc($1)
    print;
  }

The regex finds the words (and they must be alone, not part of another
word) in any case and uppercases them.  If there was a line in the file

  these students are going on a capstone experience

it would become

  THESE students are going on a capstone experience

Try it out -- it should work fine.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to