[6888] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 513 Volume: 8

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Wed May 21 22:06:07 1997

Date: Wed, 21 May 97 19:00:23 -0700
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, 21 May 1997     Volume: 8 Number: 513

Today's topics:
     Re: Change or Delete a line in a FILE (Tad McClellan)
     File Locking w/ PERL silver@silverbergcom.com
     Help with delimited fields... (Paul W. Campbell)
     Re: Help with delimited fields... <rbrannan@oakharbor.net>
     Re: How to work with data files? <mkornell@bridges.com>
     Re: How to work with data files? (Tad McClellan)
     Re: Multiple ENDs in one file. (Charles DeRykus)
     Re: Need help with sorting (Tad McClellan)
     Re: Newbie writing to a file question. (Tung-chiang Yang)
     Re: Passing Variables between Programs (Tad McClellan)
     Re: perl -e 'getpwuid 555;' ---> syntax error ? (Chipmunk)
     Re: probably a simple question (Tad McClellan)
     Q: Untainting an environment variable without changing  <apollock@bit.net.au>
     Re: Reading the last line of a file (Craig Berry)
     Re: Reading the last line of a file (I R A Aggie)
     Re: Reading the last line of a file (Tad McClellan)
     Re: running a script from a script (Chipmunk)
     Re: send input to external command? (Tad McClellan)
     Re: system calls (Tad McClellan)
     Re: system calls <usenet-tag@qz.little-neck.ny.us>
     Re: Time stamping with perl (Raul Almquist)
     Re: Time stamping with perl (Raul Almquist)
     Re: timelocal.pl ? (Raul Almquist)
     What do you do in place of 'case' or 'switch' <moody@roguewave.com>
     Re: What's the quickest way in perl to determine if a s (Andrew M. Langmead)
     Re: While loops starting with "1"? peter.hanson@stelhq.com
     Digest Administrivia (Last modified: 8 Mar 97) (Perl-Users-Digest Admin)

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

Date: Wed, 21 May 1997 18:24:00 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: Change or Delete a line in a FILE
Message-Id: <g600m5.7j3.ln@localhost>

Cheetat Yap (tat@pc.jaring.my) wrote:
: Dear Sirs/Madams

: 	Can anyone suggest a direct way to change or delete a line in the
                             ^^^^^^

No. Indirect is the way it is done, unless you want to change
for exactly the same number of characters...


: middle of a TEXT FILE.....

: 	Thanks in advance...

: ps: I did read the PERL' FAQ.
      ^^^^^^^^^^^^^^^^^^^^^^^^^


Then you must have missed this one in part 5:

"How do I change one line in a file/delete a line in a file/insert a 
line in the middle of a file/append to the beginning of a file?"


--
    Tad McClellan                          SGML Consulting
    Tag And Document Consulting            Perl programming
    tadmc@flash.net


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

Date: Wed, 21 May 1997 17:22:43 +0100
From: silver@silverbergcom.com
Subject: File Locking w/ PERL
Message-Id: <33832151.1A46@silverbergcom.com>

I am trying to make a logging perl script, and I understand I need to
lock my data file for writing in case the script gets called
simultaneously. How do I use the flock() command for this? Right now, my
script looks like:


open (LOGGER, ">>$log_file");

flock <LOGGER>, LOCK_EX;

print LOGGER "$date\t";
print LOGGER "$ENV{'REMOTE_HOST'}\t";
print LOGGER "$query_string\t";
print LOGGER "$ENV{'HTTP_USER_AGENT'}\n";

flock <LOGGER>, LOCK_EX;

close (LOGGER);


Is this correct? I have the O'Reilly perl book, but it didn't seem too
helpful.

Thanks for your help,

Eric Silverberg


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

Date: 21 May 1997 23:43:10 GMT
From: campbell@getnet.com (Paul W. Campbell)
Subject: Help with delimited fields...
Message-Id: <5m01ae$eit$1@news.getnet.com>


(sorry about the formatting)


I want to take this:
--------------------

login|98-P49344W|CFI_FB3.0|1.1|96/10/02 04:08:23||96/10/0215:29:46|sgc/bin/login|1.1|96/10/02 04:08:23||sgc/bin/login||0644||||||||||||||||||||
cshrc|98-P49344W|CFI_FB3.0|1.3|96/10/02 04:02:44||97/02/2005:28:48|sgc/bin/cshrc|1.3|96/10/02 04:02:44||sgc/bin/cshrc||0644||||||||||||||||||||


And make it look like:
----------------------

1.1             sgc/bin/login
1.3             sgc/bin/cshrc


---

As you'll note, I want only fields 9 & 8 (respectively) and it will
alwways be delimited by a "|". What is the best was to do this?


I appreciate any help!

Paul

-- 


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

Date: 22 May 1997 01:02:15 GMT
From: "Rick Brannan" <rbrannan@oakharbor.net>
Subject: Re: Help with delimited fields...
Message-Id: <5m05un$cpj$1@news7.gte.net>

Try splitting the line on the pipe, a la:
@var = split(/\|/, $login); #where $login is the login|... string below

and then reassigning the proper value(s) to your variable(s)
$newlogin = $var[9];	#where $newlogin is the value you want to keep
$logindir = $var[8]; 	#where $logindir is /sgc/bin/login

Then format the variables properly for output/report. There's probably
someone out there that could cram it all into one line for you, but I think
you get the idea ...


Paul W. Campbell <campbell@getnet.com> wrote in article
<5m01ae$eit$1@news.getnet.com>...
> I want to take this:
> --------------------
> 
> login|98-P49344W|CFI_FB3.0|1.1|96/10/02
04:08:23||96/10/0215:29:46|sgc/bin/login|1.1|96/10/02
04:08:23||sgc/bin/login||0644||||||||||||||||||||
> cshrc|98-P49344W|CFI_FB3.0|1.3|96/10/02
04:02:44||97/02/2005:28:48|sgc/bin/cshrc|1.3|96/10/02
04:02:44||sgc/bin/cshrc||0644||||||||||||||||||||
> 
> 
> And make it look like:
> ----------------------
> 
> 1.1             sgc/bin/login
> 1.3             sgc/bin/cshrc
> 
> 
> ---
 


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

Date: Wed, 21 May 1997 17:14:56 -0700
From: "Mark Kornell" <mkornell@bridges.com>
Subject: Re: How to work with data files?
Message-Id: <5m032t$o3t@fountain.mindlink.net>

Will this do?

open (MYFILE, $filename) || die ("Can't open $filename - $!");
while (<MYFILE>) {
  $_ =~ /\s+(\d+)$/;
  $Items{$1) = $2;    # if you have duplicate items in the file, then
$Items{$1) =+ $2;
}
close (MYFILE);

#now, print the list out
foreach $key (keys (%Items)) {
  print STDOUT "$key $Items{$key}\n";   
}


 cs277@columbia.edu wrote in article <3383acee.2249373@news.inx.net>...
>I have a file where on each line there is a string and a number such
>as
>
>Furniture  23
>Bedroom & kitchen 45
>Bathroom and bacement 30
>
>and so on.
>
>I want to read this into an array and change the numbers based on
>comparisons on the strings. (the strings will be the keywords for
>comparisons and when I get a match I work with the number - an
>associative
>array).  How can I do this (read the file into the associative array)?
>
>Thanks
>
>--
>Daniel
> 




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

Date: Wed, 21 May 1997 19:30:34 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: How to work with data files?
Message-Id: <a340m5.vq3.ln@localhost>

cs277@columbia.edu wrote:
: I have a file where on each line there is a string and a number such
: as

: Furniture  23
: Bedroom & kitchen 45
: Bathroom and bacement 30

: and so on.

: I want to read this into an array and change the numbers based on
: comparisons on the strings. (the strings will be the keywords for
: comparisons and when I get a match I work with the number - an
: associative
: array).  How can I do this (read the file into the associative array)?


---------------------
#! /usr/bin/perl -w

while (<DATA>) {
   ($room, $num) = /(.*) (\d+)/; # split the two parts
   $rooms{$room} = $num;         # room is key, number is value
}

foreach (sort keys %rooms)       # print 'em
   {print "$_\n"}


__DATA__
Furniture  23
Bedroom & kitchen 45
Bathroom and bacement 30
---------------------


--
    Tad McClellan                          SGML Consulting
    Tag And Document Consulting            Perl programming
    tadmc@flash.net


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

Date: Wed, 21 May 1997 23:29:16 GMT
From: ced@bcstec.ca.boeing.com (Charles DeRykus)
Subject: Re: Multiple ENDs in one file.
Message-Id: <EAK18s.A0x@bcstec.ca.boeing.com>

In article <EAGoDF.91s@nonexistent.com>, Abigail <abigail@fnx.com> wrote:
 >  [ omitted ] 
 >
 > And why does -w warn about multiple ENDs, yet multiple BEGINs
 > are allowed?
 > 

Abigail,

5.004 corrects this.


HTH,

--
Charles DeRykus
ced@carios2.ca.boeing.com


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

Date: Wed, 21 May 1997 18:41:38 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: Need help with sorting
Message-Id: <i710m5.pk3.ln@localhost>

Kathy Scott (kscott@uab.edu) wrote:
: I am trying to sort a file of collumns of numbers by a specific collumn.  I am
                                                    ^^^^^^^^^^^^^^^^^^^^^

Which one?

How are the columns defined?

Space separated?

Fixed length fields?

Other?


: having trouble figuring out what the best method is to do this.  I thought I
: would read the file in line by line and isolate the collumn of intrest into an
: array.  Then I could sort the array and go back through the file and pairing up
: the collumn data with the original file then printing to a new file.  I'm not
: sure that this would work because I don't know how to handle a situation where
: the same number appears twice in the collumn of intrest.  There would no way to
: locate the corresponding data in the original file.
: Can someone please make a suggestion how to go about fixing the double entry
: problem or a better method of sorting the file?


Sure we could, if only we had some actual data to sort...


I'll just make a WAG:


@lines = <>; # slurp all lines

foreach (sort by_col3 @lines) {
   print;
}


sub by_col3 { # I'll assume one or more space separates the columns
   $a3 = (split / +/, $a)[2];
   $b3 = (split / +/, $b)[2];
   $a3 <=> $b3;
}

This will be really slow on large lists. There is much info available
about sorting with perl in the man pages, perl FAQ, and at www.perl.com


--
    Tad McClellan                          SGML Consulting
    Tag And Document Consulting            Perl programming
    tadmc@flash.net


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

Date: Thu, 22 May 1997 00:59:21 GMT
From: tcyang@netcom.com (Tung-chiang Yang)
Subject: Re: Newbie writing to a file question.
Message-Id: <tcyangEAK5Ex.Ftu@netcom.com>

"-" has its special meaning in Perl patterns (range), so you need to
escape "-" in the pattern.  I encountered this problem in the past.

======================
Kings (rking@thepoint.net) wrote:

: (deleted)

: open (POST,">posts.html") || die "Can't Open postpath: $!\n";
: foreach $line (@lines) {
:         if ($line =~ /<!--begin-->/) {
:                 print POST "<!--begin-->\n";

: (deleted)

--
Tung-chiang Yang                       tcyang@netcom.com

soc.culture.taiwan, soc.culture.china (by SCC FAQ Team) FAQ's:
   http://www.clever.net/tcyang/Taiwan_faq.shtml, China_faq.shtml


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

Date: Wed, 21 May 1997 18:33:37 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: Passing Variables between Programs
Message-Id: <ho00m5.6k3.ln@localhost>

joet@miles33.com wrote:
:     I'm new to Perl programming, so my apologies if this is trite.
: I have a Perl wrapper which will execute two separate Perl scripts.
: The first script, when finished, needs to pass one of it's variables
: to the second script. I tried to use the return() function, but it is
: only valid between subroutines. I have looked at the Perl FAQ, but to
: no avail.

: I could do this by writing the data to a temporary disk file, or
: setting up a shared memory area (the script will run under Solaris),
: but is this the best way?

: Does anyone have any suggestions on the best way of doing this in Perl?


# script_1 writes to STDOUT
@out_from_1 = `script_1`; # backticks (backwards single quotes)
                          # use a scalar instead if you only have one value

@out_from_2 = `script_2 @out_from_1`;


: Any guidance is appreciated.


see the Perl FAQ, part 8:

-------------------
How can I capture STDERR from an external command?

There are three basic ways of running external commands:

    system $cmd;                # using system()
    $output = `$cmd`;           # using backticks (``)
    open (PIPE, "cmd |");       # using open()

 ...

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


--
    Tad McClellan                          SGML Consulting
    Tag And Document Consulting            Perl programming
    tadmc@flash.net


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

Date: 22 May 1997 00:01:41 GMT
From: Ronald.J.Kimball@dartmouth.edu (Chipmunk)
Subject: Re: perl -e 'getpwuid 555;' ---> syntax error ?
Message-Id: <5m02d5$mh4$1@dartvax.dartmouth.edu>

In article <5lqfj6$jmq@flood.weeg.uiowa.edu>
Buck Huppmann <buck@genetics.uiowa.edu> writes:

>         $ perl -we 'getpwnam "foo";'
> 
>         Number found where operator expected at -e line 1, near "getpwuid 555"
>                 (Do you need to predeclare getpwuid?)
>         syntax error at -e line 1, near "getpwuid 555"
>         Execution of -e aborted due to compilation errors.

That's weird, on my system, I get:

        $ perl -we 'getpwnam "foo";'

        String found where operator expected at -e line 1, near
"getpwnam "foo""
                (Do you need to predeclare getpwnam?)
        syntax error at -e line 1, near "getpwnam "foo""
        Execution of -e aborted due to compilation errors.

I think your first problem is figuring out why it gives you an error
for "getpwuid 555" when you're using "getpwnam "foo"".

Chipmunk


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

Date: Wed, 21 May 1997 19:17:56 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: probably a simple question
Message-Id: <kb30m5.vo3.ln@localhost>

Scott (Scott@wwide.com) wrote:

: I have a (hopefully) simple problem.  I have a perl script that reads a
: text file in one character at a time and displays it out to the web. 
: the text file is something like this:

[ snip example file ]

: what I want to do is read this file in a line at a time, and display
: only the lines that I want, ie, i want to display just the line about
: joe and the one about eric, nothing else.

: Here is how it is read in right now:
: while (read(SOCK,$charcter,1)) {       # Get a character


while ( $line = <SOCK> ) {
   

: can anyone help me? I have read the faq, went to perl.com and looked at
: dejanews for related questions and saw nothing, I went and bought "CGI
: Programming on the World Wide Web" by O'Reilly & Assoc, it seems good
: but if someone can help it would be greatly appreciated!!

--
    Tad McClellan                          SGML Consulting
    Tag And Document Consulting            Perl programming
    tadmc@flash.net


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

Date: 22 May 1997 01:41:30 GMT
From: "Andrew Pollock" <apollock@bit.net.au>
Subject: Q: Untainting an environment variable without changing it
Message-Id: <01bc6651$452a5e80$045e12cb@minotaur>

Heaven forbid that I've asked a FAQ here, but...

I'm writing a setuid CGI script that needs access to $ENV{'REMOTE_USER'}.
How can I untaint this environment variable? A perl -T is spewing when I
make a system call  using this variable as a parameter.

TIA

Andrew
-- 
----
Andrew Pollock		Programmer/System Administrator
apollock@bit.net.au	http://staff.bit.net.au/apollock
Brisbane Internet Technology Pty Ltd


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

Date: 21 May 1997 23:59:52 GMT
From: cberry@cinenet.net (Craig Berry)
Subject: Re: Reading the last line of a file
Message-Id: <5m029o$19u$1@marina.cinenet.net>

Bob Maillet (rmaillet@inigo.us.dg.com) wrote:
: I am trying to get my program to read the last line of a file..
: I have tried a loop but had no luck..does anyone have any suggestions?
: here is a chunk of what I have so far which displays all the data in the
: file..
: 
: open (FILE, $database);
: @file = (<FILE>);
: close(FILE);

$lastline = $file[-1];

Hope this helps!

---------------------------------------------------------------------
   |   Craig Berry - cberry@cinenet.net
 --*--    Home Page: http://www.cinenet.net/users/cberry/home.html
   |      Member of The HTML Writers Guild: http://www.hwg.org/   
       "Every man and every woman is a star."


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

Date: Wed, 21 May 1997 20:10:57 -0500
From: fl_aggie@hotmail.com (I R A Aggie)
Subject: Re: Reading the last line of a file
Message-Id: <fl_aggie-ya02408000R2105972010570001@news.fsu.edu>

In article <338383C8.856D7023@inigo.us.dg.com>, rmaillet@inigo.us.dg.com wrote:

+ I am trying to get my program to read the last line of a file..

One could use seek(), but that looks to be somewhat involved. Not horribly
so if you have a fixed record length.

+ open (FILE, $database);

You really should make your open()'s look like this:
   open( BLAH, $blah) or die $! 

in case something bad happens.

+ @file = (<FILE>);
+ close(FILE);

Ok, you slurp up the entire file. This is easy. The last line is:

$last_line=$file[$#file];

+ foreach $line (@file)
+ {

Dern C programmers... :)

+   $_ = $line;

Unnecessary. This form of ForEach uses $_ as the index:

foreach (@file) {
 @ok = split /","/;
}

James

-- 
Consulting Minister for Consultants, DNRC
Support the anti-Spam amendment <url:http://www.cauce.org/>
To cure your perl CGI problems, please look at:
<url:http://www.perl.com/perl/faq/idiots-guide.html>


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

Date: Wed, 21 May 1997 19:25:27 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: Reading the last line of a file
Message-Id: <np30m5.vo3.ln@localhost>

Bob Maillet (rmaillet@inigo.us.dg.com) wrote:
: I am trying to get my program to read the last line of a file..
: I have tried a loop but had no luck..does anyone have any suggestions?
: here is a chunk of what I have so far which displays all the data in the
: file..

: open (FILE, $database);
: @file = (<FILE>);
: close(FILE);


Well, since you now have the whole file slurped into an array, all you
need to know is the index of the last element in the array.

Perl is ready to give this to you:


print $file[$#file];  #   $#file is the subscript of the last element
                      #   in the @file array...

--
    Tad McClellan                          SGML Consulting
    Tag And Document Consulting            Perl programming
    tadmc@flash.net


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

Date: 22 May 1997 00:04:38 GMT
From: Ronald.J.Kimball@dartmouth.edu (Chipmunk)
Subject: Re: running a script from a script
Message-Id: <5m02im$mh4$2@dartvax.dartmouth.edu>

In article <864077683.5297@dejanews.com>
liamtu@echonyc.com writes:

> I need to get the result of a perl script for use in a perl script... when
> I open the file in perl I just get the script text. I know there must be a
> simple answer.

If you just open it, you're not executing it.

If you want to execute it, you have to do something like:

$result = `perl.script`;

Chipmunk


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

Date: Wed, 21 May 1997 19:22:44 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: send input to external command?
Message-Id: <kk30m5.vo3.ln@localhost>

Yi Wang (wang16@fas.harvard.edu) wrote:
: Once you call an external command which also will be waiting an input,
: how do you pass the input inside the script?


You open a pipe to the command:


open (CMDIN, "| cat") || die "could not fork";

print CMDIN "Four score\n";
print CMDIN "And seven years ago...\n";


: Thanks much in advance.


You're welcome.


--
    Tad McClellan                          SGML Consulting
    Tag And Document Consulting            Perl programming
    tadmc@flash.net


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

Date: Wed, 21 May 1997 18:35:20 -0500
From: tadmc@flash.net (Tad McClellan)
Subject: Re: system calls
Message-Id: <or00m5.6k3.ln@localhost>

Greg (galoi@sdcc13.ucsd.edu) wrote:

: I was wondering how to make certain system calls from within a perl
: script.  For example how could I make a call to the unix command
: "date" and store the value returned by "date" in a variable?


By reading the Perl FAQ, part 8:


------------------------
=head2 How can I capture STDERR from an external command?

There are three basic ways of running external commands:

    system $cmd;                # using system()
    $output = `$cmd`;           # using backticks (``)
    open (PIPE, "cmd |");       # using open()

 ...

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


--
    Tad McClellan                          SGML Consulting
    Tag And Document Consulting            Perl programming
    tadmc@flash.net


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

Date: 22 May 1997 01:37:41 GMT
From: Eli the Bearded <usenet-tag@qz.little-neck.ny.us>
Subject: Re: system calls
Message-Id: <5m0815$7um$1@news.netusa.net>

In article <5lvilo$ec2@sdcc13.ucsd.edu>, Greg <galoi@sdcc13.ucsd.edu> wrote:
>I was wondering how to make certain system calls from within a perl
>script.  For example how could I make a call to the unix command
>"date" and store the value returned by "date" in a variable?

That is a system command, not a system call. "localtime" to get the
current time is what you want anyway for that example. When you want
to run a system command use either "system('stty cbreak >/dev/tty');"
or backticks: "$vimcompile=`vim -c ':version|q'`;"

Elijah
------
system calls are documented in section 2 of the manpages


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

Date: Wed, 21 May 1997 16:46:26 -0600
From: strider@ShadowMAC.org (Raul Almquist)
Subject: Re: Time stamping with perl
Message-Id: <strider-ya02408000R2105971646260001@news.winternet.com>

In article <5lto46$p28@panix.com>, clay@panix.com (Clay Irving) wrote:

> In <338210AD.5920@wind-river.com> Nicholas Hardgrove
<nickh@wind-river.com> writes:
> 
> >Can anyone tell me how to get a time stamp from the system so that I can
> >add it into database info that I am working on?
> 
> Could it be as easy as:
> 
>   $timestamp = localtime();

  Don't know about him, but not for mine that's for sure.  I found

($sec, $min, $hour, $day, $mon, $yr, $wday, $yday, $isdst) = localtime (time);
$month = ($mon + 1);
$year = ($yr + 1900);
$time = sprintf ("%02d:%02d:%02d", $hour, $min, $sec);
$date = sprintf ("19%02d-%02d-%02d", $year, $month, $day);

to accomplish things well enough.


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

Date: Wed, 21 May 1997 16:44:59 -0600
From: strider@ShadowMAC.org (Raul Almquist)
Subject: Re: Time stamping with perl
Message-Id: <strider-ya02408000R2105971644590001@news.winternet.com>

In article <338210AD.5920@wind-river.com>, nickh@wind-river.com wrote:

> Can anyone tell me how to get a time stamp from the system so that I can
> add it into database info that I am working on?

  Funny, that was what I was working at doing too.  Below is what I did, it
may do what you need.


($sec, $min, $hour, $day, $mon, $yr, $wday, $yday, $isdst) = localtime (time);
$month = ($mon + 1);
$year = ($yr + 1900);
$time = sprintf ("%02d:%02d:%02d", $hour, $min, $sec);
$date = sprintf ("19%02d-%02d-%02d", $year, $month, $day);

then just put in $date and $time where ever you need to do the time stamping.

enjoy


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

Date: Wed, 21 May 1997 16:39:34 -0600
From: strider@ShadowMAC.org (Raul Almquist)
Subject: Re: timelocal.pl ?
Message-Id: <strider-ya02408000R2105971639340001@news.winternet.com>

In article <strider-ya02408000R2005971558080001@news.winternet.com>,
strider@ShadowMAC.org (Raul Almquist) wrote:

  Thanks all, but I figured out what I needed about an hour after my
posting, what I did is as follows...  nothing fancy though.

($sec, $min, $hour, $day, $mon, $yr) = localtime (time);
$month = ($mon + 1);
$year = ($yr + 1900);
$time = sprintf ("%02d:%02d:%02d", $hour, $min, $sec);
$date = sprintf ("%04d-%02d-%02d", $year, $month, $day);


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

Date: Wed, 21 May 1997 17:03:24 -0700
From: Steve Moody <moody@roguewave.com>
Subject: What do you do in place of 'case' or 'switch'
Message-Id: <33838D4C.4E9A@roguewave.com>

I see that there is not a "case" or "switch" statement
in Perl. That puzzles me since that is a fairly common construct
in other languages. I figure that there must be an equivalent that
I am overlooking or am unaware of.

What I am needing to do is to parse out a series of command
line options, and based on their value enact a specific routine
within my program. In C this was handled nicely with "switch"
statements in ksh with "case" statements.

So what do yall do in Perl? Hmm...?
I am hoping that some wonderous nugget awaits and that
my fears of "if" ladders are unjustified.

I am sure that you have dealt with this before and if the
question appears newbie-ish... well it is. I have my pen and paper
ready (or rather my keyboard and screen) please share some 
of your wisdom with me. And if I must be resigned to a 
"if" hell then hopefully some of you can make the pain more
bearable.

In any case thanks in advance for your help and assistance
please email me to the address below in addition to posting 
to the group.

Thanks one and all
-- 
***************************
Steve Moody             
Configuration Librarian 
Rogue Wave Software     
moody@roguewave.com 
(541) - 754 - 3297    
***************************


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

Date: Thu, 22 May 1997 00:53:38 GMT
From: aml@world.std.com (Andrew M. Langmead)
Subject: Re: What's the quickest way in perl to determine if a scalar is a list?
Message-Id: <EAK55E.n1C@world.std.com>

[a copy of this was e-mailed to Paul a few days ago. Since his
publicly posted article just showed up in my news spool today, I
didn't realize that I was stealth-CC'd]

Paul Lussier <plussier@synnet.com> writes:
> 
> I never said my answers were better than the FAQ.  As a matter of fact, I
> never even said my answers were good, and I did suggest that the poster
> refer to the manual.  Someone asked a question, and trying to be helpful,
> I gave some simple examples of how the problem could be solved.  

Usenet FAQ articles are supposed to be consise, well researched,
correct, answers to common questions. Giving buggy, inneficient,
solutions instead of pointing the person to the FAQ is not being
helpful to the questioner, not helpful to the other people reading the
newsgroup and know the right answer, and not helpful to anybody else
who might take your information as fact.

> > Besides, #1 could be an average of 50% faster if you put a "last"
> > statement inside the "if". (Also a but faster if you said foreach
> 				     ^^^
> 	You mean a "bit"?
> 
> I did use a foreach.
> 
> > (@array). 

You're right about my typo. I did mean "bit" not "but". On the other
hand, you mangled my point. I wasn't saying that foreach would have
been faster than what you did, I said that "foreach(@array)" is faster
than "forach(0 .. $#array)". The first takes an existing list and
aliases the foreach iterator to the list element. The second creates a
temporary array of numbers, 0 through $#array. Then it aliases the
iterator to each successive elements of the temp list. Finally, in
your code, you use the iterator to index into @array. So your method
pratically doubles the memory usage of the script (For each element of
@array, there needs to be a corresponding element created in the
anonymous list created by 0 .. $#array.) Takes the execution time to
create and initialize each element, and the extra time for the
indexing into the array.

> > All of your solutions have the bug that occurs when $string contains
> > regular expression metacharacters.
> 
> Well, like I said, I never guaranteed that they were perfect.  I also
> don't often encounter the need to match strings that have embedded
> metacharacters, nor did the original poster mention that this was a
> concern.  

But how can you guarantee what the user types in? Should your script
immediately die with "unmatched [] in regexp at buggyscript line 42,
<> chunk 1." if the user makes a typo? Especially since it could be
fixed so easily with

       /\Q$string\E/o;  
> 
> Thanks for taking the time to point out my mistakes though.  I love it
> when some one can show me mistakes, since that will help me write better
> code in the future.

I'm not sure if you understand the big mistake that I was pointing
out. Try not to reinvent answer FAQs. If its answer is better than
yours, then point the poster to the FAQ. If your answer is better than
the FAQs, mail it to the FAQ maintainer for inclusion in later
versions.
-- 
Andrew Langmead


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

Date: Wed, 21 May 1997 19:34:22 -0600
From: peter.hanson@stelhq.com
Subject: Re: While loops starting with "1"?
Message-Id: <864259447.13055@dejanews.com>

In article <3380AD7C.249BD411@ibm.net>,
  Markus Schlegel <markus@ibm.net> wrote:

>
> I recently saw a strange construct, looking like this:
>
> # put commas in the right places in an integer
>
> 1 while s/ (\d) (\d\d\d) (!?\d)/($1,$2);
>
> (From "programming Perl", O'Reilly)
>
> My question here is: Is the "1" in this line used as a
> boolean, and if so, why is this legal, since this doesn't
> look conform to any "while" statement I have used so far.

Say it ain't so, Markus!  It's merely using while as a
statement modifier.  I.e.,

   expr1 while expr2;

means the same as:

   while (expr2) { expr1; }

Never mind if expr1 is something goofy like  1  or  ()
or even "Let Randal Go!".

Lazy PERL programmers (is any other kind worth knowing?)
like to use this form for simple loops; you don't need the
parends or braces, for one thing.

By the way, the s/// in expr2 is using the default argument ($_),
so you can stuff your input in, and read your output from, there.

This is often convenient -- $_ is the default for many operations.
This may be a natural place for your input or output or both.

Then again, this may mean $_ is being used for something else!
In that case, you can use =~ as described in any PERL manual.

-------------------==== Posted via Deja News ====-----------------------
      http://www.dejanews.com/     Search, Read, Post to Usenet


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

Date: 8 Mar 97 21:33:47 GMT (Last modified)
From: Perl-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 8 Mar 97)
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.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 513
*************************************

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