[11377] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 4977 Volume: 8

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Fri Feb 26 11:37:38 1999

Date: Fri, 26 Feb 99 08:31:45 -0800
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Fri, 26 Feb 1999     Volume: 8 Number: 4977

Today's topics:
        HELP: goin' crazy with subarrays! <soli@pc-szoftver.mgx.hu>
    Re: HELP: goin' crazy with subarrays! <thelma@alpha2.csd.uwm.edu>
    Re: HELP: goin' crazy with subarrays! (Tad McClellan)
    Re: HELP: inverse log? <aliceo@cs.cmu.edu>
        HELP: Pattern matching. - Thanks to all who helped :) networks@skynet.co.uk
        HELP: Pattern matching. networks@skynet.co.uk
        HELP: Pattern matching. networks@skynet.co.uk
        HELP: Pattern matching. networks@skynet.co.uk
    Re: HELP: Pattern matching. <kenhirsch@myself.com>
    Re: HELP: Pattern matching. <staffan@ngb.se>
    Re: HELP: Pattern matching. (M.J.T. Guy)
        Help: Setting Perl ENV so Apache can log correctly havenskys@my-dejanews.com
    Re: Help: Setting Perl ENV so Apache can log correctly (Bill Moseley)
        Heuristics, anyone? (Carl Spalletta)
    Re: Heuristics, anyone? (Ronald J Kimball)
    Re: Heuristics, anyone? <gellyfish@btinternet.com>
    Re: Heuristics, anyone? (Peter Roozemaal)
    Re: Heuristics, anyone? <monty@primenet.com>
        How can I write to an unpadded format field? chrisw2679@my-dejanews.com
    Re: How can I write to an unpadded format field? <rick.delaney@home.com>
        How do I compare scalar to array entry <wmwilson1@go.com>
    Re: How do I compare scalar to array entry (Larry Rosler)
    Re: How do I compare scalar to array entry (Clinton Pierce)
    Re: How do I compare scalar to array entry <m.v.wilson@erols.com>
    Re: how do i declare file PERMISSION within the perl sc <aqumsieh@matrox.com>
        Special: Digest Administrivia (Last modified: 12 Dec 98 (Perl-Users-Digest Admin)

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

Date: Tue, 23 Feb 1999 13:51:15 +0100
From: soli <soli@pc-szoftver.mgx.hu>
Subject: HELP: goin' crazy with subarrays!
Message-Id: <36D2A443.9E721C24@pc-szoftver.mgx.hu>

Hi All,

I am absolutely new to Perl. I am trying to create an array,
with arrays within them. (called hashes of lists???)
Sometimes (always?) I need to test if a given item exists in one of the
subarrays. I show you my prog, and its output. You will see the
problem. So:

#!/usr/bin/perl
%LOL=();

sub IsItem {
    local(@table, $element) = @_;
    $result = -1;

    foreach  $item(@table) { print "$item\t\n"; }

    for ($i=0; $i<$#table+1; $i++) {
        print $i,"! ",$table[$i],"\n";
        if ($table[$i] eq @_[1]) {
            $result=$i;
            #$i=$#table+1;
        }
    }
    return $result;
}


$LOL{soli} = ["Nirvana","Pearl Jam","Soundgarden"];
$LOL{nobody}= ["SQL","PERL","JAVA"];
$LOL{theking}= ["Buda","Pest","Sopron"];
$LOL{mittomen}= ["Peach","Grape","Apple"];

push @{ $LOL{"soli"} }, "Red Hot Chili Peppers";

print "IsItem(..)=",IsItem(@{ $LOL{soli} }, "Red Hot Chili Peppers"),
"\n";


THE OUTPUT IS:
---------- Perl ----------
Nirvana
Pearl Jam
Soundgarden
Red Hot Chili Peppers
Red Hot Chili Peppers
0! Nirvana
1! Pearl Jam
2! Soundgarden
3! Red Hot Chili Peppers
4! Red Hot Chili Peppers
IsItem(..)=1
Normal Termination
Output completed (0 sec consumed).

------------------------------------
As you see,
    - the PUSHed element seems to be duplicated!
    - the "IsItem" func always return 1.

Why???

Please help, my boss is hurrying me all the day to make some
"logfile proccessing" for him.

[Reply to my address, too]

Thanks in advance,
SOLI



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

Date: 23 Feb 1999 14:03:04 GMT
From: Thelma Lubkin <thelma@alpha2.csd.uwm.edu>
Subject: Re: HELP: goin' crazy with subarrays!
Message-Id: <7auceo$v8r$1@uwm.edu>

soli <soli@pc-szoftver.mgx.hu> wrote:
: Hi All,

: I am absolutely new to Perl. I am trying to create an array,
: with arrays within them. (called hashes of lists???)
: Sometimes (always?) I need to test if a given item exists in one of the
: subarrays. I show you my prog, and its output. You will see the
: problem. So:

: #!/usr/bin/perl
     use #!/usr/bin/perl -w  :This gives you warnings of places where
                              code is syntactically acceptable, but
                              may not mean what you think it does--in
                              this case it would have given you a few
                              hints...
: %LOL=();

: sub IsItem {
:     local(@table, $element) = @_;
           perl expands all parameters, so you are passing
           (#table+1)+1 parameters, not 2. But since the first
           item to get those elements in the sub is an array, it
           picks up *all* of @_ -- $element remains undefined: -w
           would have told you that.  So @table is one element
           bigger than you think it is: its final entry is what
           you thought you were putting into $element, and that's
           why you're printing that final element twice.

:     $result = -1;

:     foreach  $item(@table) { print "$item\t\n"; }

:     for ($i=0; $i<$#table+1; $i++) {
:         print $i,"! ",$table[$i],"\n";
:         if ($table[$i] eq @_[1]) {   ####@_[1] is $table[1] (see above)
:             $result=$i;              ####that's why it reports 1
:             #$i=$#table+1;
:         }
:     }
:     return $result;
: }


: $LOL{soli} = ["Nirvana","Pearl Jam","Soundgarden"];
: $LOL{nobody}= ["SQL","PERL","JAVA"];
: $LOL{theking}= ["Buda","Pest","Sopron"];
: $LOL{mittomen}= ["Peach","Grape","Apple"];

: push @{ $LOL{"soli"} }, "Red Hot Chili Peppers";

: print "IsItem(..)=",IsItem(@{ $LOL{soli} }, "Red Hot Chili Peppers"),
: "\n";


: THE OUTPUT IS:
: ---------- Perl ----------
: Nirvana
: Pearl Jam
: Soundgarden
: Red Hot Chili Peppers
: Red Hot Chili Peppers
: 0! Nirvana
: 1! Pearl Jam
: 2! Soundgarden
: 3! Red Hot Chili Peppers
: 4! Red Hot Chili Peppers
: IsItem(..)=1
: Normal Termination
: Output completed (0 sec consumed).

: ------------------------------------
: As you see,
:     - the PUSHed element seems to be duplicated!
:     - the "IsItem" func always return 1.

: Why???

: Please help, my boss is hurrying me all the day to make some
: "logfile proccessing" for him.

: [Reply to my address, too]

: Thanks in advance,

           Hope this is enough to get you on with it
                        --thelma
: SOLI



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

Date: Tue, 23 Feb 1999 04:18:32 -0500
From: tadmc@metronet.com (Tad McClellan)
Subject: Re: HELP: goin' crazy with subarrays!
Message-Id: <8prta7.b43.ln@magna.metronet.com>

soli (soli@pc-szoftver.mgx.hu) wrote:

: I am absolutely new to Perl. 


   Then you should become accustomed to taking advantage of the
   hundreds of pages of Perl reference material that comes with
   the perl distribution.

   They are called POD (Plain Old Documentation) files.

   They are more up-to-date than *any* Perl book.

   They are easily searched (with a printed book, if your word isn't
   in the index, you're stuck).

   Find out where they are on your system (look for a .pod filename
   extension) and use them often.



: I am trying to create an array,
: with arrays within them. (called hashes of lists???)


   That is called a List of Lists.

   One of the above mentioned pod files is named 'perllol.pod' and
   is titled "Manipulating Lists of Lists in Perl".

   Having a look at that one would be Really Good.


: Sometimes (always?) I need to test if a given item exists in one of the
: subarrays. 


   Another of the above mentioned pod files named 'perlfaq4.pod'
   has the complete and verified answer to your Frequently Asked
   Question:

      "How can I tell whether a list or array contains a certain element?"



: I show you my prog, and its output. You will see the
: problem. So:

: #!/usr/bin/perl


   There are 2 problems already.

      1) you are missing the -w switch

      2) you are missing the 'use strict;' pragma


: %LOL=();

: sub IsItem {
:     local(@table, $element) = @_;

   Yet another of the above mentioned pod files named 'perlsub.pod'
   describes subroutines in Perl.

   It describes how arguments are passed to Perl subroutines:

-----------------
The Perl model for function call and return values is simple: all
functions are passed as parameters one single flat list of scalars, and
all functions likewise return to their caller one single flat list of
scalars.  Any arrays or hashes in these call and return lists will
collapse, losing their identities--but you may always use
pass-by-reference instead to avoid this.
-----------------

   Try printing the value of $element at this point.

   It has no value.

   You need to change the order of your arguments in both the definition
   and the call.

   You should always use my() instead of local() unless you know
   what the difference is.
    
   You never use $element anywhere else anyway. The -w switch would
   have warned you about that.


      my($element, @table) = @_;


:     for ($i=0; $i<$#table+1; $i++) {


   style suggestion:

      for ($i=0; $i<=$#table; $i++) {
                   ^^^^

   or

      for ($i=0; $i<@table; $i++) {
                   ^^


:         print $i,"! ",$table[$i],"\n";
:         if ($table[$i] eq @_[1]) {
                            ^
                            ^
   You are using an "array slice" there, but you do not want to
   be using an array slice. You want to test a single scalar.
   Scalar names always start with a dollar sign.

      if ($table[$i] eq $_[1]) {
                        ^

   But I don't know why you are accessing @_ directly when you
   already copied everthing into my() variables with meaningful names.



: print "IsItem(..)=",IsItem(@{ $LOL{soli} }, "Red Hot Chili Peppers"),
: "\n";


: THE OUTPUT IS:
: ---------- Perl ----------
: Nirvana
: Pearl Jam
: Soundgarden
: Red Hot Chili Peppers
: Red Hot Chili Peppers
: 0! Nirvana
: 1! Pearl Jam
: 2! Soundgarden
: 3! Red Hot Chili Peppers
: 4! Red Hot Chili Peppers
: IsItem(..)=1
: Normal Termination
: Output completed (0 sec consumed).

: ------------------------------------
: As you see,
:     - the PUSHed element seems to be duplicated!
:     - the "IsItem" func always return 1.

: Why???


   Because $_[1] is the second element of @table, not the same as $element.


: Please help, my boss is hurrying me all the day to make some
: "logfile proccessing" for him.


   You can get answers *hundreds of times faster* if you first take
   the time to check the applicable parts of the standard Perl docs
   before resorting to the really slow method of posting to Usenet.


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


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

Date: Thu, 25 Feb 1999 04:56:13 -0500
From: "Alice Oh" <aliceo@cs.cmu.edu>
Subject: Re: HELP: inverse log?
Message-Id: <7b36d4$g80$1@goldenapple.srv.cs.cmu.edu>

never mind.
i just realized how stupid this question is....
hey, it's almost 5 am. and i'm frantically trying to get a project done.

thanks anyway.

Alice Oh wrote in message <7b35r9$g2n$1@goldenapple.srv.cs.cmu.edu>...
>Is there a function to get the inverse log (base 2) of a number?
>
>thanks in advance.
>
>




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

Date: Tue, 23 Feb 1999 23:03:15 GMT
From: networks@skynet.co.uk
Subject: HELP: Pattern matching. - Thanks to all who helped :)
Message-Id: <36d3331c.8921523@news.skynet.co.uk>

Help much appreciated

Thanks 


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

Date: Tue, 23 Feb 1999 16:09:13 GMT
From: networks@skynet.co.uk
Subject: HELP: Pattern matching.
Message-Id: <36d2d29f.22518584@news.skynet.co.uk>

Hi,

Can you help me with this problem. I've got a script that will search
a tab delimted text file for a sting match e.g. the site visitor can
enter a sting in a statndard html form, the string is passsed to the
perl script which search the text file for a match. This is what I've
done so far:

	while (defined($line = <DATAFILE>))
	{
		($name,$link) = split(/\t/,$line);
		if ($name eq $find)

		{	
			$url{$link} = $name;
		}
	}

This works fine of exact matches, but I'd like the script to return
all the lines which match the search string: e.g.

The user enters the string: DUKE

the text file contains two lines like this:

DUKE NUKEN	www....
DUKE NUKEN TIME TO KILL	www....

I'd like the script to return both lines to the results page.


Help much appreciated

Thanks 


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

Date: Tue, 23 Feb 1999 12:54:04 GMT
From: networks@skynet.co.uk
Subject: HELP: Pattern matching.
Message-Id: <36d2a179.9935356@news.skynet.co.uk>

Hi,

Can you help me with this problem. I've got a script that will search
a tab delimted text file for a sting match e.g. the site visitor can
enter a sting in a statndard html form, the string is passsed to the
perl script which search the text file for a match. This is what I've
done so far:

	while (defined($line = <DATAFILE>))
	{
		($name,$link) = split(/\t/,$line);
		if ($name eq $find)

		{	
			$url{$link} = $name;
		}
	}

This works fine of exact matches, but I'd like the script to return
all the lines which match the search string: e.g.

The user enters the string: DUKE

the text file contains two lines like this:

DUKE NUKEN	www....
DUKE NUKEN TIME TO KILL	www....

I'd like the script to return both lines to the results page.


Help much appreciated

Thanks 


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

Date: Tue, 23 Feb 1999 14:23:43 GMT
From: networks@skynet.co.uk
Subject: HELP: Pattern matching.
Message-Id: <36d2b9dd.16179646@news.skynet.co.uk>

Hi,

Can you help me with this problem. I've got a script that will search
a tab delimted text file for a sting match e.g. the site visitor can
enter a sting in a statndard html form, the string is passsed to the
perl script which search the text file for a match. This is what I've
done so far:

	while (defined($line = <DATAFILE>))
	{
		($name,$link) = split(/\t/,$line);
		if ($name eq $find)

		{	
			$url{$link} = $name;
		}
	}

This works fine of exact matches, but I'd like the script to return
all the lines which match the search string: e.g.

The user enters the string: DUKE

the text file contains two lines like this:

DUKE NUKEN	www....
DUKE NUKEN TIME TO KILL	www....

I'd like the script to return both lines to the results page.


Help much appreciated

Thanks 


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

Date: Tue, 23 Feb 1999 11:30:34 -0500
From: "Ken Hirsch" <kenhirsch@myself.com>
Subject: Re: HELP: Pattern matching.
Message-Id: <7aul1u$44e$1@fir.prod.itd.earthlink.net>


networks@skynet.co.uk wrote in message
>This works fine of exact matches, but I'd like the script to return
>all the lines which match the search string: e.g.
>


Replace
  if ($name eq $find) {
with
  if ($name =~ /$find/) {

see the perlre and perlop man pages for details on pattern matching.






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

Date: Tue, 23 Feb 1999 17:54:02 +0100
From: Staffan Liljas <staffan@ngb.se>
Subject: Re: HELP: Pattern matching.
Message-Id: <36D2DD2A.33EA79F0@ngb.se>

networks@skynet.co.uk wrote:
>         while (defined($line = <DATAFILE>))
>         {
>                 ($name,$link) = split(/\t/,$line);
>                 if ($name eq $find)
> 
>                 {
>                         $url{$link} = $name;
>                 }
>         }

Try

    my(@lines, @matches);
    @lines = <DATAFILE>;
    @matches = grep(/$find/, @lines);

now matches has the lines you want.

You could also try reading the docs, especially perlfunc and perlre

HTH Staffan


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

Date: 23 Feb 1999 23:57:00 GMT
From: mjtg@cus.cam.ac.uk (M.J.T. Guy)
Subject: Re: HELP: Pattern matching.
Message-Id: <7avf8c$8b4$1@pegasus.csx.cam.ac.uk>

Ken Hirsch <kenhirsch@myself.com> wrote:
>
>networks@skynet.co.uk wrote in message
>>This works fine of exact matches, but I'd like the script to return
>>all the lines which match the search string: e.g.
>>
>
>
>Replace
>  if ($name eq $find) {
>with
>  if ($name =~ /$find/) {

To avoid nasty surprises, make that

   if ($name =~ /\Q$find/) {

As a rule of thumb, variable interpolation in patterns should always be
preceded by \Q, unless you *know* you want otherwise.

Pity it isn't the default.


Mike Guy


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

Date: Thu, 25 Feb 1999 17:56:13 GMT
From: havenskys@my-dejanews.com
Subject: Help: Setting Perl ENV so Apache can log correctly
Message-Id: <7b42rm$7rr$1@nnrp1.dejanews.com>

The Log configuration in httpd.conf supports using environment variables by
entering '%{PATH}e' into the log configuration, Apache prints out the
$ENV{'PATH'} variable.

Problem:  Apache only print to the log what $ENV{'PATH'} was originally.  This
is no good.  $ENV{'PATH'} is originally "/bin:/usr/local/bin" and even if I
change it like this:

$ENV{'PATH'} = "/bin";

It still prints what it was originally.

Question:  Is there some way to set the environment variables so that Apache
will log the correct information?

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own    


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

Date: Thu, 25 Feb 1999 10:21:38 -0800
From: moseley@best.com (Bill Moseley)
Subject: Re: Help: Setting Perl ENV so Apache can log correctly
Message-Id: <MPG.113f348d29853e7b9896bb@206.184.139.132>

In article <7b42rm$7rr$1@nnrp1.dejanews.com>, havenskys@my-dejanews.com 
says...
> The Log configuration in httpd.conf supports using environment variables by
> entering '%{PATH}e' into the log configuration, Apache prints out the
> $ENV{'PATH'} variable.
> 
> Problem:  Apache only print to the log what $ENV{'PATH'} was originally.  This
> is no good.  $ENV{'PATH'} is originally "/bin:/usr/local/bin" and even if I
> change it like this:
> 
> $ENV{'PATH'} = "/bin";


I assume you are setting this in a CGI program...

That's YOUR environment your setting in Perl.  Not the one Apache sees.


-- 
Bill Moseley mailto:moseley@best.com


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

Date: Mon, 22 Feb 1999 02:57:34 GMT
From: nectarsys@home.com (Carl Spalletta)
Subject: Heuristics, anyone?
Message-Id: <36d0c2dd.8607957@news>

 
  I use shell, awk and perl interchangeably, and I like them all, but
I know that use of awk and shell is deprecated by some perlites, even
in trivial cases.  Is this a legitimate point of view?

  Is it generally true that awk is better for short one-liners?

$ #16 characters vs 29, not bad.
$ awk '{print $5}'
$#123456789012345678901234567890
$ perl -a -ne 'print "$F[4]\n"'

  I was just wondering if there are any well known heuristics for
deciding when to use each language.


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

Date: Sun, 21 Feb 1999 23:29:34 -0500
From: rjk@linguist.dartmouth.edu (Ronald J Kimball)
Subject: Re: Heuristics, anyone?
Message-Id: <1dnlnfc.esejsy12jiwk0N@bay2-148.quincy.ziplink.net>

Carl Spalletta <nectarsys@home.com> wrote:

> $ #16 characters vs 29, not bad.
> $ awk '{print $5}'
> $#123456789012345678901234567890
> $ perl -a -ne 'print "$F[4]\n"'

    perl -alpe'$_=$F[4]'

20 characters, I think that's about as short as you can get it.  :-)

>   I was just wondering if there are any well known heuristics for
> deciding when to use each language.

Use whichever one you prefer.  Also, note the following from perlfaq6:

   I put a regular expression into $/ but it didn't work. What's wrong?

   $/ must be a string, not a regular expression.  Awk has to be better
   for something. :-)

-- 
 _ / '  _      /         - aka -          rjk@linguist.dartmouth.edu
( /)//)//)(//)/(     Ronald J Kimball      chipmunk@m-net.arbornet.org
    /                                  http://www.ziplink.net/~rjk/
        "It's funny 'cause it's true ... and vice versa."


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

Date: 22 Feb 1999 23:15:00 -0000
From: Jonathan Stowe <gellyfish@btinternet.com>
Subject: Re: Heuristics, anyone?
Message-Id: <7asodk$3u4$1@gellyfish.btinternet.com>

In comp.lang.perl.misc Carl Spalletta <nectarsys@home.com> wrote:
>  
>   I use shell, awk and perl interchangeably, and I like them all, but
> I know that use of awk and shell is deprecated by some perlites, even
> in trivial cases.  Is this a legitimate point of view?
> 

No. One will use the best available tools for the task at hand.  

I might use :

gellyfish@gellyfish:/home/gellyfish > ls -l | awk 'BEGIN { total = 0;} { total = total + $5 } END { print total }'
7732861

For instance, rather than its Perl equivalent for a simple task - *if I'm 
going to do it as a one liner*.  For myself if I'm going to start an editor
and save it then I will almost certainly do it in Perl.

/J\
-- 
Jonathan Stowe <jns@btinternet.com>
Some of your questions answered:
<URL:http://www.btinternet.com/~gellyfish/resources/wwwfaq.htm>
Hastings: <URL:http://www.newhoo.com/Regional/UK/England/East_Sussex/Hastings>


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

Date: Mon, 22 Feb 1999 21:25:35 +0100
From: mathfox@xs4all.nl (Peter Roozemaal)
Subject: Re: Heuristics, anyone?
Message-Id: <19990222.212535.32@mathfox.xs4all.nl>

In message <36d0c2dd.8607957@news> Carl Spalletta wrote:

>   I use shell, awk and perl interchangeably, and I like them all, but
> I know that use of awk and shell is deprecated by some perlites, even
> in trivial cases.  Is this a legitimate point of view?
[...]
>   I was just wondering if there are any well known heuristics for
> deciding when to use each language.

There are no simple heuristics of when to use which language; it depends
on the project, platform and required functionality which language (or
combination of languages) is best.

An incomplete list of aspects that I consider when choosing a language:
 - availability: is a good enough implementation of the language available
 		 on all target platforms (ksh on the Mac?)
 - fitness: can the task be done in the language (network programming in awk?)
 - availability of reusable code (libraries, frameworks)
 - cost of implementation: how difficult is it in the language (how many hours
 			   of coding and debugging)
 - performance: will the program run fast enough (usually not the prime
 		concern)

My manager has some different concerns:
 - vendor support for the language
 - maintainability of the code
 - availability of competent programmers

In general a manager wants to limit the number of languages and tools used
in a project, to prevent maintainance problems when the local <name your
obscure language here> wizzard leaves the project and a replacement can't
be found.

In my current project we use sh/ksh, awk, sql, c, oracle forms and perl
(in that order...); we prefer awk over perl because awk is a generic UNIX
tool and has better vendor support.
I use shell scripts for work on "file level"; when I need to handle
individual lines in files in a way the standard UNIX tools can't handle
I choose awk. C is for network and system programming.

Peter

-- 
Peter Roozemaal
 ... Hey, don't ask me, I'm just an Anthropomorphic Personification.


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

Date: 22 Feb 1999 06:14:39 GMT
From: Jim Monty <monty@primenet.com>
Subject: Re: Heuristics, anyone?
Message-Id: <7aqskf$pr1$2@nnrp03.primenet.com>

Carl Spalletta <nectarsys@home.com> wrote:
> I use shell, awk and perl interchangeably, and I like them all, but
> I know that use of awk and shell is deprecated by some perlites, even
> in trivial cases. Is this a legitimate point of view?
>
> Is it generally true that awk is better for short one-liners?

In the range of tasks for which either an awk one-liner or a Perl
one-liner could be used, the awk one-liner will invariably be
shorter, more succinct, more intuitive, more readable (especially
for non-programmers trying to figure out what the script is doing),
and less magical than the equivalent Perl one-liner.

The range of tasks that can be accomplished in one line of Perl is
far, far greater than the range of tasks that can be accomplished
in one line of awk.

For these reasons, and for many, many others, the answer to the
question "Which is better?" can only be answered subjectively.

But, yeah, generally, awk is better for one-liners.

> $ #16 characters vs 29, not bad.
> $ awk '{print $5}'
> $#123456789012345678901234567890
> $ perl -a -ne 'print "$F[4]\n"'

A clear example of the comparative brevity, succinctness, intuitiveness,
readability, and unmagicalness of awk.

By the way, 'perl -an' is just Perl in awk emulation mode.

It's hard to beat the simplicity and elegance of awk one-liners
like these:

$ awk '{ total += $5 } END { print total }'
$ awk '{ count[$5]++ } END { for (item in count) print item, count[item] }'

> I was just wondering if there are any well known heuristics for
> deciding when to use each language.

There are none. I would recommend that you simply let your intuition
be your guide, but then I know that, statistically, your intuition
will lead you to the wrong choice most of the time. This is why
you are, statistically, probably running Microsoft Windows,
programming in Visual Basic, listening to Garth Brooks, and eating
at Red Lobster. (I'm talking about statistical "you," not you "you.")

-- 
Jim Monty
monty@primenet.com
http://www.primenet.com/~monty/
Tempe, Arizona USA


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

Date: Fri, 26 Feb 1999 01:02:23 GMT
From: chrisw2679@my-dejanews.com
Subject: How can I write to an unpadded format field?
Message-Id: <7b4rqp$vec$1@nnrp1.dejanews.com>

I would like to make a form letter generator in perl to which I can supply the
person's name.  It looks something like this:

#!/usr/bin/perl
$name = "Joe Blow";
write;
format STDOUT =
Dear @<<<<<<<<<<,
$name
  You may have won a million dollars.
 .


The trouble is I'm getting "Dear Joe Blow   ," with the padded spaces in there
to fill up the <<< markers.
I can't seem to find anything in perlform that tells me how to make it print
just "Dear Joe Blow,"  I tried to do something like
format STDOUT =
Dear @<<<<<<<<<<<
$name ,
  You may have won a million dollars.
 .
(not exactly my script, but close) so that the $name would print followed by a
",".  Of course I got a bareword error in my real script as I couldn't do a
"$name yada yada"

Am I missing something in the format?  Is there a secret character other than
<

> or | I can use after the @ sign?  Or am I going about this using the wrong

tool and I should go back to using the print statement?  I don't really want
to do that as it makes the form letter unreadable.

Also, is there an easy way to do a if statement under a format?  I would like
to do something like this:  print "zone..."  print "  master: a.b.c.d" if
($type =~ /slave/); in a format.  I worked up this: $ifmaster = ($type =~
/slave/) ? "master: a.b.c.d" : ""; format STDOUT = zone... ~@<<<<<<<<<<<<<<<<
$ifmaster .

But that looks pretty messy.  Any ideas?

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own    


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

Date: Fri, 26 Feb 1999 03:42:29 GMT
From: Rick Delaney <rick.delaney@home.com>
Subject: Re: How can I write to an unpadded format field?
Message-Id: <36D61A05.6CBAA9BA@home.com>

[posted & mailed]

chrisw2679@my-dejanews.com wrote:
> 
> I would like to make a form letter generator in perl to which I can 
> supply the person's name.  It looks something like this:
> 
> #!/usr/bin/perl
> $name = "Joe Blow";
> write;
> format STDOUT =
> Dear @<<<<<<<<<<,
> $name
>   You may have won a million dollars.
> .
> 
> The trouble is I'm getting "Dear Joe Blow   ," with the padded spaces 
> in there to fill up the <<< markers.

print <<EOF;
Dear $name,
  You may have won a million dollars.
EOF

[snip]

> Or am I going about this using the wrong tool and I should go back to 
> using the print statement?  I don't really want to do that as it makes 
> the form letter unreadable.

Oh.  In that case how about

$name .= ',';
format STDOUT =
Dear @<<<<<<<<<<
$name
  You may have won a million dollars.
 .

> Also, is there an easy way to do a if statement under a format?  I 
> would like to do something like this:  print "zone..."  print "  
> master: a.b.c.d" if ($type =~ /slave/); in a format.  I worked up 
> this: $ifmaster = ($type =~ /slave/) ? "master: a.b.c.d" : ""; format 
> STDOUT = zone... ~@<<<<<<<<<<<<<<<< $ifmaster .
> 
> But that looks pretty messy.

I'll say.  You should try formatting your code as well as your data. 
:-)

>   Any ideas?

You can build up your format in a string and then eval it as suggested
in perlform.  But I think in your case you're just talking about
changing the value ot the variables interpreted into your format.  If
so, simply set them before the write.

-- 
Rick Delaney
rick.delaney@home.com


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

Date: Thu, 25 Feb 1999 19:40:33 GMT
From: Mike Wilson <wmwilson1@go.com>
Subject: How do I compare scalar to array entry
Message-Id: <7b48vf$dr4$1@nnrp1.dejanews.com>

I've got this program, I swear it worked yesterday (could be wrong though),
but I know it doesn't work right today, the major problem appears to be in
how I compare a scalar and an array, but I'm not positive, here's a snippet
to give a general idea..

while(1) {

	while(<CMD>) {
		@seen = ();

		if(!/a good line/) {

			my @entry = split(/\s+/, $_);

			if ($tty_user{$entry[1]}) {

				#seen him
				push(@seen, $entry[1]);

			} else {

				$tty_user{$entry[1]} = $entry[0];
				push(@seen, $entry[1]);

			}

		}

	}

	&delete_exited;

}

  ***This is where I think the problem is, it's deleting the key even when
it's not suppose to, from what I've figured out, it recognizes the hash
values just fine, pushes to my @seen hash just fine (hash key and array
element are equal), but I guess I'm not comparing the two below quite right,
because it decides that it doesn't see $key in @seen and deletes $key.***

sub delete_exited {

        foreach my $key (sort keys(%tty_user)) {

                if($key !~ @seen) {

                        delete $tty_user{$key};

                }

        }

}

Any help would be great, Thanks.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own    


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

Date: Thu, 25 Feb 1999 13:21:50 -0800
From: lr@hpl.hp.com (Larry Rosler)
Subject: Re: How do I compare scalar to array entry
Message-Id: <MPG.113f5ecbae33659b98968c@nntp.hpl.hp.com>

[Posted and a courtesy copy mailed.]

In article <7b48vf$dr4$1@nnrp1.dejanews.com> on Thu, 25 Feb 1999 
19:40:33 GMT, Mike Wilson <wmwilson1@go.com> says...
 ...
>                 if($key !~ @seen) {

This compares $key agains the *size* (number of elements) in @seen, 
which is surely not what you want.

                  if ($key !~ /@seen/) {

The regex here is the string resulting from join(' ', @seen), so $key 
cannot match against that either (it is a substring).  I guess you could 
reverse it like this:

                  if ("@seen" !~ /\b\Q$key\E\b/) {

which is pretty ugly but would probably work (it's easy to show 
failures).

But all of this is the result of using a poor algorithm.   Instead of 
maintaining an array @seen, you should maintain a hash %seen.  Then your 
test becomes simply this:

                  if (exists $seen{$key}) {

-- 
Larry Rosler
Hewlett-Packard Company
http://www.hpl.hp.com/personal/Larry_Rosler/
lr@hpl.hp.com


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

Date: Thu, 25 Feb 1999 20:33:52 GMT
From: clintp@geeksalad.org (Clinton Pierce)
Subject: Re: How do I compare scalar to array entry
Message-Id: <36d8aeb3.879030634@news.ford.com>

On Thu, 25 Feb 1999 19:40:33 GMT, Mike Wilson <wmwilson1@go.com>
wrote:
>I've got this program, I swear it worked yesterday (could be wrong though),
>but I know it doesn't work right today, the major problem appears to be in
>how I compare a scalar and an array, but I'm not positive, here's a snippet
>to give a general idea..

Cool.  Let's nitpick!  :-)

>while(1) {
>	while(<CMD>) {
>		@seen = ();

You spend the whole loop building @seen (and populating %tty_user),
and yet you clear it at the top of each loop.  What's @seen being used
for inside of the loop, anyways?

>		if(!/a good line/) {
>			my @entry = split(/\s+/, $_);
>			if ($tty_user{$entry[1]}) {

If you want to see if a key is present in a hash, use the exists()
function:
			if (exists $tty_user{$entry[1]}) {

Otherwise you create keys all over the hash, when you really just want
to see if it's there.

>				#seen him
>				push(@seen, $entry[1]);
>			} else {
>				$tty_user{$entry[1]} = $entry[0];
>				push(@seen, $entry[1]);
>			}
>		}
>	}
>	&delete_exited;
>}

>  ***This is where I think the problem is
>sub delete_exited {
>        foreach my $key (sort keys(%tty_user)) {
>                if($key !~ @seen) {

This does not do what you might think it does.  

It's comparing the scalar $key as a regular expression match to....
@seen... which is being used in a scalar (?) context and would be the
number of items in @seen.  so...egads.

I have no idea how that's gonna parse.  Can't imagine that "-w"
wouldn't squawk at this.  Are you just trying to see if $key is in
@seen?  If that's the case, and that's all you're using @seen for,
then keep @seen as a hash, and this test can be re-written as:

		if (exists $seen{$key}) {
		}

Of course, you'll have to fix the subroutine above...This is much more
efficient (on the programmer) than keeping @seen as a list and having
to search it sequentially to see if it has the entry you're interested
in.

>                        delete $tty_user{$key};
>                }
>        }
>}

-- 
 Clinton A. Pierce    "If you rush a Miracle Man, you get rotten
                         miracles" --Miracle Max, The Princess Bride
clintp@geeksalad.org   http://www.geeksalad.org


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

Date: Thu, 25 Feb 1999 22:14:49 +0000
From: Mike Wilson <m.v.wilson@erols.com>
To: Clinton Pierce <clintp@geeksalad.org>
Subject: Re: How do I compare scalar to array entry
Message-Id: <36D5CB59.7A085D4C@erols.com>

Clinton Pierce wrote:

>                 if (exists $seen{$key}) {
>                 }
> 
> Of course, you'll have to fix the subroutine above...This is much more
> efficient (on the programmer) than keeping @seen as a list and having
> to search it sequentially to see if it has the entry you're interested
> in.
> 
> >                        delete $tty_user{$key};
> >                }
> >        }
> >}
> 
> --
>  Clinton A. Pierce    "If you rush a Miracle Man, you get rotten
>                          miracles" --Miracle Max, The Princess Bride
> clintp@geeksalad.org   http://www.geeksalad.org

  Thanks so much, man I knew I was screwing something up there. 
Actually, just so you don't think I'm a loser based on the content of my
posting, the program does quite a bit more than that while also pushing
the @seen array, etc.
  
  Basically it tracks new logins, if it's a brand-new login it does one
thing, if the guy's been there a while it does something different. 
This is all based on parsing the `who` command, and the only way I could
see to tell if someone had left (without having to re-open the who
command) was to push them into a list and then compare who's in the
hash(which everyone's added to at first log-in) to who's just been seen
during the last iteration through `who`.  This is the reason I empty the
@seen list at the top of every loop.  Thanks again for the help, most
excellent of you.

-- 
m.v.wilson@erols.com
	Homer:	What?!  Flanders!  You're the Devil?
	
	Devil Flanders:
		Ho-oh, it's always the one you least suspect.


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

Date: Mon, 22 Feb 1999 13:20:06 -0500
From: Ala Qumsieh <aqumsieh@matrox.com>
Subject: Re: how do i declare file PERMISSION within the perl script??
Message-Id: <x3ysobys3l5.fsf@tigre.matrox.com>


justin <jjpark@home.com> writes:

> this is what i have:
> open(RECORD, ">$filename") || die "Cannot open $filename for write: $!";
> 
> print RECORD "--content--";
> 
> the file is created for the first time when running this code, and it
> automatically declares 644 as file permission.
> once the file is created with 644, it doesn't allow me to change it.
> how can i create a file with 777?

What do you mean it doesn't allow you to change it? What do you mean
by "change it" ? You mean edit it? Read from it? Write to it?

The way you open()ed your file causes the file to be created, if it
doesn't exist, or truncated to zero length if it does exist. So, if
you have old data in the file, and you open() it the way you do above,
you will lose all the data. Also, it
doesn't allow you to read from the file. You can only write to it. If
this is what you want, then it's fine, else consult perlfunc for more
info on how to use open() to do what you want.

Moreover, if you are the owner of the file, mode 644 allows you to
read from and write to it. But it allows all other people to only read
it. There is no reason to chmod 777 (which can be quite dangerous)
because this would allow anyone to modify your file (even delete
it). But, if you desperately want to chmod() then just do that. Use
chmod() ('perldoc -f chmod' for more info).

HTH,
Ala



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

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


Administrivia:

Well, after 6 months, here's the answer to the quiz: what do we do about
comp.lang.perl.moderated. Answer: nothing. 

]From: Russ Allbery <rra@stanford.edu>
]Date: 21 Sep 1998 19:53:43 -0700
]Subject: comp.lang.perl.moderated available via e-mail
]
]It is possible to subscribe to comp.lang.perl.moderated as a mailing list.
]To do so, send mail to majordomo@eyrie.org with "subscribe clpm" in the
]body.  Majordomo will then send you instructions on how to confirm your
]subscription.  This is provided as a general service for those people who
]cannot receive the newsgroup for whatever reason or who just prefer to
]receive messages via e-mail.

The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc.  For subscription or unsubscription requests, send
the single line:

	subscribe perl-users
or:
	unsubscribe perl-users

to almanac@ruby.oce.orst.edu.  

To submit articles to comp.lang.perl.misc (and this Digest), send your
article to perl-users@ruby.oce.orst.edu.

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

To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.

The Meta-FAQ, an article containing information about the FAQ, is
available by requesting "send perl-users meta-faq". The real FAQ, as it
appeared last in the newsgroup, can be retrieved with the request "send
perl-users FAQ". Due to their sizes, neither the Meta-FAQ nor the FAQ
are included in the digest.

The "mini-FAQ", which is an updated version of the Meta-FAQ, is
available by requesting "send perl-users mini-faq". It appears twice
weekly in the group, but is not distributed in the digest.

For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V8 Issue 4977
**************************************

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