[24615] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 6791 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Sun Jul 11 14:05:41 2004

Date: Sun, 11 Jul 2004 11:05:07 -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           Sun, 11 Jul 2004     Volume: 10 Number: 6791

Today's topics:
    Re: aliased shell commands from perl script <nobull@mail.com>
    Re: CGI: print $x =~ s/\n/<br>\n/g; (J. Romano)
        date problem <gabriell@programmer.net>
    Re: date problem <noreply@gunnar.cc>
    Re: date problem <bob@dont.spam.me>
    Re: date problem <jurgenex@hotmail.com>
    Re: date problem (Peter J. Acklam)
    Re: date problem (Peter J. Acklam)
    Re: date problem <cfajohnson@gmail.com>
    Re: how perl set envirment variable (J. Romano)
    Re: how perl set envirment variable <jurgenex@hotmail.com>
    Re: how perl set envirment variable <1usa@llenroc.ude>
        LAMP - Program Design with Perl (Dieter)
    Re: LAMP - Program Design with Perl (Anno Siegel)
        looping through array <bobsmith@[no-thankyou-very-much]jippii.fi>
    Re: looping through array <jds@atavailcheck.com>
    Re: looping through array <abigail@abigail.nl>
    Re: Negation of RegEx (Dan)
    Re: Regexp substitution problem - suggestions? <nobull@mail.com>
    Re: Regexp substitution problem - suggestions? <1usa@llenroc.ude.invalid>
    Re: Using scalar() on function return values (J. Romano)
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: 11 Jul 2004 18:31:49 +0100
From: Brian McCauley <nobull@mail.com>
Subject: Re: aliased shell commands from perl script
Message-Id: <u9hdse1md6.fsf@wcl-l.bham.ac.uk>

d_v_g@usa.net (Dmitry) writes:

> I has faced a problem of calling shell aliases from a perl script recently.
> Web search gave me almost nothing, so I feel obliged to share my results
> with community :-)  The only way, which made perl script to execute my tcsh
> aliases is below.  I would very appreciate if anybody, who knows a better
> method, posted it here.

Perhaps your mistake was to look for Perl solutuions.  The solution is
more dependant on the languge being called than the language doing the
calling.

In general if you wish one program written in some language to cause a
script to be interpreted by a script interpreter for some other
language you need to pass the script in the other language interpreter
in one of three ways:

  1 A pipe (if the interpreter supports reading from STDIN).
  2 A temporary file (as you did).
  3 On the command line (if the interpreter supports it).

Of these (3) is the simplest where it is possible. The exact what yo
do this depends on the interpreter you want to call.  With the Perl
interpreter the switch used to pass the the script as a command line
argument is -e . In many other interpreters (including most (all?)
Unix shells) it is -c.


> use strict;
> use Cwd;
> use Env;
> 
> my( $n_args )   = 0;
> my( $own_name ) = "";
> my( $user_cmd ) = "";
> my( $n_sec )    = 0;
> my( $ali )      = "";
> my( $kb )       = "";

You are suffering premature declaration.

[ snip ]

> my( $tmp_fname ) = "KILLME.kill";

There are better ways to get a temporary file BTW.
 
> open( OUT, ">$tmp_fname" ) || die ( "Can't open file for writing: $!" );
> print OUT "source ~/.aliases";
> print OUT "\n";
> print OUT $user_cmd;
> print OUT "\n";
> close( OUT );

[ snip ]

>    system( "tcsh $tmp_fname" );  # execute commands from a file

More simply

system ('tcsh','-c',"source ~/.aliases; $user_cmd");

-- 
     \\   ( )
  .  _\\__[oo
 .__/  \\ /\@
 .  l___\\
  # ll  l\\
 ###LL  LL\\


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

Date: 11 Jul 2004 09:52:56 -0700
From: jl_post@hotmail.com (J. Romano)
Subject: Re: CGI: print $x =~ s/\n/<br>\n/g;
Message-Id: <b893f5d4.0407110852.41950b54@posting.google.com>

Ken Sington <ken_sington@nospam_abcdefg.com> wrote in message news:<SKednRPN4rj4oXLdRVn-tw@speakeasy.net>...
> In this test:
> 
> This: print $x =~ s/\n/<br>\n/g;
> 
> doesn't do this:
> $x =~ s/\n/<br>\n/g;
> print $x;

   You are correct.  Your confusion probably comes from the fact that
the line:

      print $x =~ s/\n/<br>\n/g;

looks like the line:

      print $x = 5;

but behaves nothing like it.

   When you say "$x = 5", the "=" operator changes the value of $x and
returns the same value (so it is the value of $x that gets printed
with the print() function).  The "=~" operator, on the other hand,
changes the value of $x but does NOT return the value of $x. 
According "perldoc perlop", it returns the number of substitutions
made (when used with s///), which is rarely what it sets $x to.

   Therefore, the number of substitutions made is what gets passed to
the print() function, instead of the new value of $x, as you had
thought.

   I hope this helps,

   -- J.


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

Date: Sun, 11 Jul 2004 16:21:38 +0200
From: Gabkin <gabriell@programmer.net>
Subject: date problem
Message-Id: <2ld0nlFat4f1U1@uni-berlin.de>

I need to generate a date in the format YYYYMMDDHHMMSSS for a perl 
program. (Note the _three_ digits allocated for Seconds, not the usual 
_two_)

date +%Y%m%d%H%M%S will give YYYYMMDDHHMMSS which is close but it doesnt 
have that extra S at the end.

I am using "date (sh-utils) 2.0.15" and "perl, v5.8.2" on Cygwin.

Is there a quick and easy way of getting that extra degree of precision 
with 'date'?
Failing that, a way to get it with perl?

Thanks


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

Date: Sun, 11 Jul 2004 16:40:01 +0200
From: Gunnar Hjalmarsson <noreply@gunnar.cc>
Subject: Re: date problem
Message-Id: <2ld1hcFb7is0U1@uni-berlin.de>

Gabkin wrote:
> I need to generate a date in the format YYYYMMDDHHMMSSS for a perl
> program. (Note the _three_ digits allocated for Seconds, not the
> usual _two_)

<snip>

> Is there a quick and easy way of getting that extra degree of
> precision with 'date'?

> Failing that, a way to get it with perl?

In Perl there is the Time::HiRes module.

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl


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

Date: Sun, 11 Jul 2004 14:41:06 GMT
From: Bob <bob@dont.spam.me>
Subject: Re: date problem
Message-Id: <pan.2004.07.11.14.41.05.94713@dont.spam.me>

On Sun, 11 Jul 2004 16:21:38 +0200, Gabkin wrote:

> I need to generate a date in the format YYYYMMDDHHMMSSS for a perl
> program. (Note the _three_ digits allocated for Seconds, not the usual
> _two_)
> 
> date +%Y%m%d%H%M%S will give YYYYMMDDHHMMSS which is close but it doesnt
> have that extra S at the end.
> 
> I am using "date (sh-utils) 2.0.15" and "perl, v5.8.2" on Cygwin.
> 
> Is there a quick and easy way of getting that extra degree of precision
> with 'date'?
> Failing that, a way to get it with perl?
> 
> Thanks

Precision? There will never be more than two digits in the seconds field
(00-60 -- yes, 60. See man date!). If for some reason you want to force
an extra high-order 0 do the following:

	date +%Y%m%d%H%M0%S

The format string can contain arbitrary text, a "0" in the above.

But, perhaps I don't understabd what you want. Note that "+%s" (lowercase
s) gives seconds since 1970 (at least for GNU version of date).


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

Date: Sun, 11 Jul 2004 15:03:30 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: date problem
Message-Id: <6FcIc.9985$ju1.1519@nwrddc04.gnilink.net>

Gabkin wrote:
> I need to generate a date in the format YYYYMMDDHHMMSSS for a perl
> program. (Note the _three_ digits allocated for Seconds, not the usual
> _two_)
>
> date +%Y%m%d%H%M%S will give YYYYMMDDHHMMSS which is close but it
> doesnt have that extra S at the end.

Well, hmmm, when I look at my watch the possible values for seconds range
from 0 to 59. This is only _two_ digits which implies that your additional
third digit would always be zero.
Something along the line of
    s/(..)$/0$1/
should add that digit.

jue




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

Date: 11 Jul 2004 17:16:18 +0200
From: pjacklam@online.no (Peter J. Acklam)
Subject: Re: date problem
Message-Id: <pt72k20t.fsf@online.no>

Gabkin <gabriell@programmer.net> wrote:

> I need to generate a date in the format YYYYMMDDHHMMSSS for a
> perl program. (Note the _three_ digits allocated for Seconds,
> not the usual _two_)
> 
> date +%Y%m%d%H%M%S will give YYYYMMDDHHMMSS which is close but
> it doesnt have that extra S at the end.

Assuming the third S is for deciseconds, try the Time::HiRes
module.  If you have it installed, try

   perldoc Time::HiRes

Peter

-- 
#!/local/bin/perl5 -wp -*- mode: cperl; coding: iso-8859-1; -*-
# matlab comment stripper (strips comments from Matlab m-files)
s/^((?:(?:[])}\w.]'+|[^'%])+|'[^'\n]*(?:''[^'\n]*)*')*).*/$1/x;


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

Date: 11 Jul 2004 17:21:08 +0200
From: pjacklam@online.no (Peter J. Acklam)
Subject: Re: date problem
Message-Id: <iscuk1sr.fsf@online.no>

Bob <bob@dont.spam.me> wrote:

> On Sun, 11 Jul 2004 16:21:38 +0200, Gabkin wrote:
> 
> > Is there a quick and easy way of getting that extra degree of
> > precision with 'date'?
> 
> Precision? There will never be more than two digits in the
> seconds field (00-60 -- yes, 60. See man date!).

"Precision" is the number of digits relative to the decimal point.
Higher precision means more digits after the decimal point, i.e.,
higher resolution.  For instance, a precision of 3 would include
milliseconds.

Peter

-- 
#!/local/bin/perl5 -wp -*- mode: cperl; coding: iso-8859-1; -*-
# matlab comment stripper (strips comments from Matlab m-files)
s/^((?:(?:[])}\w.]'+|[^'%])+|'[^'\n]*(?:''[^'\n]*)*')*).*/$1/x;


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

Date: 11 Jul 2004 17:21:36 GMT
From: "Chris F.A. Johnson" <cfajohnson@gmail.com>
Subject: Re: date problem
Message-Id: <2ldb90Fb4mi4U1@uni-berlin.de>

On 2004-07-11, Gabkin wrote:
> I need to generate a date in the format YYYYMMDDHHMMSSS for a perl 
> program. (Note the _three_ digits allocated for Seconds, not the usual 
> _two_)
>
> date +%Y%m%d%H%M%S will give YYYYMMDDHHMMSS which is close but it doesnt 
> have that extra S at the end.
>
> I am using "date (sh-utils) 2.0.15" and "perl, v5.8.2" on Cygwin.
>
> Is there a quick and easy way of getting that extra degree of precision 
> with 'date'?

date +%Y%m%d%H%M%03S

-- 
    Chris F.A. Johnson                  http://cfaj.freeshell.org/shell
    ===================================================================
    My code (if any) in this post is copyright 2004, Chris F.A. Johnson
    and may be copied under the terms of the GNU General Public License


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

Date: 11 Jul 2004 09:08:29 -0700
From: jl_post@hotmail.com (J. Romano)
Subject: Re: how perl set envirment variable
Message-Id: <b893f5d4.0407110808.569601c9@posting.google.com>

> jl_post@hotmail.com (J. Romano) wrote in
> news:b893f5d4.0407100619.7a09dd66@posting.google.com: 
> > 
> >    All I did was set the PATH by setting $ENV{PATH}, and then adding
> > "exec $ENV{SHELL}" as the last line of the Perl script.  That way,
> > your environment changes will "stick" when the Perl script ends.

"A. Sinan Unur" <1usa@llenroc.ude> replied in message
news:<Xns952271F924AAasu1cornelledu@132.236.56.8>...
> 
> Changes will not stick. You have just invoked a new copy of your shell 
> with  a new environment.

   You're right:  Changes will not stick -- to the old shell.  But the
old shell is not around anymore, and what's left to work with is a new
shell that's practically identical to the old shell but with the
environment changes you made in the Perl script.

   It's kind of like a joke I heard once:  A robber broke into a house
and stole all the furniture and appliances -- but he replaced them
with exact copies.

   The point of the joke is that if the robber replaced everything
with an exact copy, how is that any different (from the rightful
owner's point of view) from the thief not stealing anything at all to
begin with?

   In the same way, you might be concerned that a new copy of your
shell was invoked (replacing the old shell), but if the new shell is
almost identical to the old shell, would that really matter?

   As it turns out, it does matter in some matter in some cases. 
Jürgen Exner pointed out that Perl is often used in batch programming,
in which case the commands after the call to the Perl script would run
in the parent shell and not have the environment changes.  But then,
if the Perl script was invoked with the "exec" command, the commands
after the call to the Perl script wouldn't get run at all (not to
mention, the Perl script's line "exec $ENV{SHELL}" would open up a new
shell, which is not wanted in batch scripting).

> Each time you run this script, a new copy of your shell will run. 
> 
> Why would you want to do that for something that can be handled much for 
> easily using your shell's facilities?

   (I assume you meant "... much *more* easily ...")

   I'll give you an example:

   Several times during working on Unix systems (both at the
university and at work) I've had to execute a specific shell script in
order to begin a certain task or run a certain program.  This shell
script was provided by the professor or a system administrator, and it
would made changes to my environment ensuring me being able to run the
program needed for me to get my work done.  (I would have to execute
this shell script once for each terminal window I had open.)

   One problem with these scripts was that they would often add paths
to my $PATH environment variable.  They would usually add the
"/usr/bin" path as well as a few X11 paths, even though I already had
them in my $PATH.  And often these scripts would call other scripts
(which sometimes would call more scripts) that other professors or
system administrators wrote, and each one of these scripts would add
new entires to my $PATH.  So after I ran the one script my professor
(or system administrator) required us to run, my $PATH would have
dozens of duplicate paths.

   You can argue that you should check to see if a path already exists
before adding it to the $PATH.  That's a valid point, but I didn't
write these scripts, nor did I have the permissions to change them. 
As Derek Ludwig said:

> I have to deal with too many "helpful" people who
> correct the value of ${PATH}

   This is where the following script comes in handy:

#!/usr/bin/perl -w
# File:  simplifyPath.pl
use strict;
my %seen;  # store paths already seen
my @pathList = split /:/, $ENV{PATH};
@pathList = grep { ! $seen{$_}++ } @pathList;
$ENV{PATH} = join ':', @pathList;
exec $ENV{SHELL};
__END__

   Now I can run:

      exec syimplifyPath.pl

and there will be no more duplicates in my path, leaving me free to
work on my task with all the environment changes I wanted (in this
case, the one made to my $PATH).

   Could I write a program that does the same thing in another shell
script language?  Yes, I could -- and I did.  I wrote a "simplifyPath"
script (I think in csh) a few years ago before I knew Perl -- but let
me tell you:  it was much more difficult to write it in csh.

   But maybe there is an easier way to do this using a non-Perl shell
script.  And if there is, I'd like to see it.  But since I've had the
exact problem I just stated to you (several times in the past), I'm
inclined to think that posters like Ting Wang have the same problem,
while others are inclined to think that he (or she?) is running Perl
in as part of another script, and that opening an interactive child
shell is unacceptable.

   Unfortunately, our friend Ting Wang was rather vague about the
situation (he/she didn't even specify what platform he/she was using),
making it hard to suggest a suitable solution for him/her.

   But to say that the solution I proposed is worthless because of
some side effect (that may or may not be an issue to the poster) is to
neglect any Perl programmer looking for a working solution to the same
dilemma I had.  Not everyone has a problem with those side-effects, so
it's unreasonable to think that just because some people do, then
everyone does.

   I hope this explains things.

   -- Jean-Luc


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

Date: Sun, 11 Jul 2004 16:34:06 GMT
From: "Jürgen Exner" <jurgenex@hotmail.com>
Subject: Re: how perl set envirment variable
Message-Id: <2_dIc.41707$Xq4.17783@nwrddc02.gnilink.net>

J. Romano wrote:
>> jl_post@hotmail.com (J. Romano) wrote in
>> news:b893f5d4.0407100619.7a09dd66@posting.google.com:
>>>
>>>    All I did was set the PATH by setting $ENV{PATH}, and then adding
>>> "exec $ENV{SHELL}" as the last line of the Perl script.  That way,
>>> your environment changes will "stick" when the Perl script ends.
>
> "A. Sinan Unur" <1usa@llenroc.ude> replied in message
> news:<Xns952271F924AAasu1cornelledu@132.236.56.8>...
>>
>> Changes will not stick. You have just invoked a new copy of your
>> shell with  a new environment.
>
>    You're right:  Changes will not stick -- to the old shell.  But the
> old shell is not around anymore,

Oh, no. It is still very much around. Check the process table.

> and what's left to work with is a new
> shell that's practically identical to the old shell but with the
> environment changes you made in the Perl script.

Not at all. The new shell has a different process ID (which might screw up
processed, that rely on the process ID to e.g. identify temporary files), it
has a different command history, it may be executing a different shell
script (if any!), if doesn't continue where the old shell script called the
Perl script.
>
>    It's kind of like a joke I heard once:  A robber broke into a house
> and stole all the furniture and appliances -- but he replaced them
> with exact copies.
>
>    The point of the joke is that if the robber replaced everything
> with an exact copy, how is that any different (from the rightful
> owner's point of view) from the thief not stealing anything at all to
> begin with?

If the robber stole your antic furnitures and replaced them with new copies,
then I guess you would notice the difference, wouldn't you?

>    In the same way, you might be concerned that a new copy of your
> shell was invoked (replacing the old shell), but if the new shell is
> almost identical to the old shell, would that really matter?

It does. Very much so.

>    As it turns out, it does matter in some matter in some cases.
> Jürgen Exner pointed out that Perl is often used in batch programming,
> in which case the commands after the call to the Perl script would run
> in the parent shell and not have the environment changes.

Ok, glad to see that you do understand the shortcomings of your approach.

> But then,
> if the Perl script was invoked with the "exec" command,

Why would anyone do that? Typically you want a process to call the Perl
script to do some task and then call the next script or program to do the
next task and so on. If you call the sub-scripts using exec() then I
certainly don't want to manage the control flow of that system.

> the commands
> after the call to the Perl script wouldn't get run at all (not to
> mention, the Perl script's line "exec $ENV{SHELL}" would open up a new
> shell, which is not wanted in batch scripting).
>
>> Each time you run this script, a new copy of your shell will run.

>    Several times during working on Unix systems (both at the
> university and at work) I've had to execute a specific shell script in
> order to begin a certain task or run a certain program.  This shell
> script was provided by the professor or a system administrator, and it
> would made changes to my environment ensuring me being able to run the
> program needed for me to get my work done.  (I would have to execute
> this shell script once for each terminal window I had open.)
>
>    One problem with these scripts was that they would often add paths
> to my $PATH environment variable.  They would usually add the
> "/usr/bin" path as well as a few X11 paths, even though I already had
> them in my $PATH.  And often these scripts would call other scripts
> (which sometimes would call more scripts) that other professors or
> system administrators wrote, and each one of these scripts would add
> new entires to my $PATH.  So after I ran the one script my professor
> (or system administrator) required us to run, my $PATH would have
> dozens of duplicate paths.

So what? What is the problem with that?

[...]
>    This is where the following script comes in handy:
[Perl script to remove duplicate entries in PATH]
> $ENV{PATH} = join ':', @pathList;
> exec $ENV{SHELL};
>
>    Now I can run:
>
>       exec syimplifyPath.pl

If instead of the exec() you would have done a
    print 'set path="' .  join (':', @pathList) . '"';
and then eval'ed the output of the Perl script in your original shell, then
you would not have needed a new shell with all the nasty side effects.

jue




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

Date: 11 Jul 2004 16:34:46 GMT
From: "A. Sinan Unur" <1usa@llenroc.ude>
Subject: Re: how perl set envirment variable
Message-Id: <Xns95237FF70EBC9asu1cornelledu@132.236.56.8>

jl_post@hotmail.com (J. Romano) wrote in
news:b893f5d4.0407110808.569601c9@posting.google.com: 

>> jl_post@hotmail.com (J. Romano) wrote in
>> news:b893f5d4.0407100619.7a09dd66@posting.google.com: 
>> > 
>> >    All I did was set the PATH by setting $ENV{PATH}, and then
>> >    adding 
>> > "exec $ENV{SHELL}" as the last line of the Perl script.  That way,
>> > your environment changes will "stick" when the Perl script ends.
> 
> "A. Sinan Unur" <1usa@llenroc.ude> replied in message
> news:<Xns952271F924AAasu1cornelledu@132.236.56.8>...
>> 
>> Changes will not stick. You have just invoked a new copy of your
>> shell with  a new environment.
> 
>    You're right:  Changes will not stick -- to the old shell.  But the
> old shell is not around anymore, and what's left to work with is a new
> shell that's practically identical to the old shell but with the
> environment changes you made in the Perl script.
> 
>    It's kind of like a joke I heard once:  A robber broke into a house
> and stole all the furniture and appliances -- but he replaced them
> with exact copies.
> 
>    The point of the joke is that if the robber replaced everything
> with an exact copy, how is that any different (from the rightful
> owner's point of view) from the thief not stealing anything at all to
> begin with?

The fact that the owner has the right to shoot the robber while he is in 
the process.

>    In the same way, you might be concerned that a new copy of your
> shell was invoked (replacing the old shell), but if the new shell is
> almost identical to the old shell, would that really matter?

It does not replace the old shell. The old shell is still taking memory 
(however virtual it is).

>> Each time you run this script, a new copy of your shell will run. 
>> 
>> Why would you want to do that for something that can be handled much
>> for easily using your shell's facilities?
> 
>    (I assume you meant "... much *more* easily ...")

Yes :)

>    I'll give you an example:
> 
>    Several times during working on Unix systems (both at the
> university and at work) I've had to execute a specific shell script in
> order to begin a certain task or run a certain program.

 ...

>    One problem with these scripts was that they would often add paths
> to my $PATH environment variable.
 ...

> So after I ran the one script my professor (or system administrator) 
> required us to run, my $PATH would have dozens of duplicate paths.

The solution to that is to start a new shell, run the scripts and do 
whatever your professor asks of you etc, then exit that shell. 

Or, screen (http://www.gnu.org/software/screen/) might be useful.

Anyway, this is where we stand and I am going to stop before carrying 
this thread any more off-topic than I have done with some others :)

-- 
A. Sinan Unur
1usa@llenroc.ude (reverse each component for email address)


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

Date: 11 Jul 2004 03:13:58 -0700
From: affenkopf2004@yahoo.de (Dieter)
Subject: LAMP - Program Design with Perl
Message-Id: <34dd0a89.0407110213.e124c3a@posting.google.com>

Hi,

here I'd like to ask for your advice how to
generally code a certain task, not for the details.

O.K.- I try to express myself clearly:

* There's a HTML-form from which the user can choose
many different options (about 15) simultanously in 
all possible combinations for a variable number of items
(batch mode).

So e.g. lets say, she can enter "apple, peach, cherry"
and request "color, taste, shape, short description"
out of a set of many other options.

* The CGI-script constructs a statement, depending on the desired 
information and queries the MySQL database.

* Depending on what kind of information was requested,
the output from the database is formatted differentially
(headers, linebreaks ... ) and sent to the user.


Now, the system already runs fine just for a few options.
But with a about 15 options in different combinations
I don't want to end up with endless numbers of "if"-clauses.

Do you know a elegant solution, how to manage all the
different optional parameters ?

The problem appears on three stages:

* Parsing the POST data (request)
* Constructing the query for the database
* Handling the output


Maybe there are Perl modules to faciliate this kind of task ?


Dieter


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

Date: 11 Jul 2004 13:40:29 GMT
From: anno4000@lublin.zrz.tu-berlin.de (Anno Siegel)
Subject: Re: LAMP - Program Design with Perl
Message-Id: <ccrg0d$hlh$1@mamenchi.zrz.TU-Berlin.DE>

Dieter <affenkopf2004@yahoo.de> wrote in comp.lang.perl.misc:

[...]

> Now, the system already runs fine just for a few options.
> But with a about 15 options in different combinations
> I don't want to end up with endless numbers of "if"-clauses.

Time for a timeless quote:  "I don't know what your problem is,
but I suggest using a hash"

Seriously, if a cascade of if/elsif spins out of control, a hash is
often the solution.

> Do you know a elegant solution, how to manage all the
> different optional parameters ?

Consider a hash along these lines:

    my %options = (
        apple => [ qw( size color taste) ],
        car   => [ qw( size color seats fuel) ],
        # ...
    );

Note that a hash can also contain code to deal with specific situations.
Such a thing is called a dispatch table, and it is a very powerful tool.

Instead of writing

    if ( $thing eq 'apple' ) {
        # code to deal with apple
    } elsif ( $thing eq 'car' ) {
        # code to deal with car
    } elsif ( ... ) {

you can construct a hash

   my %action = (
       apple => sub {
                    # code to deal with apple
                },
       car   => sub {
                    # code to deal with car
                },
       # ...
   );

and replace the entire if/elsif construct with

    $action{ $thing}->();

Using hashes along these lines is one of the standard techniques in Perl
to deal with complex branching based on string values.  It is very
maintainable when options (possible string values) are added, removed
or changed.

Anno


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

Date: Sun, 11 Jul 2004 14:34:58 +0200
From: svenne <bobsmith@[no-thankyou-very-much]jippii.fi>
Subject: looping through array
Message-Id: <Vr9Ic.2902$wV2.2361@reader1.news.jippii.net>

Hi all,
this is trivvial question but how do you compare existense of elements intwo
arrays?, that is I want to compare two arrays and check the existense of
the first array's elements in the second array, 

one line of code if possible...

any advice much appreciated, thank you.
/G
--
www.gh-webinteractive.com
 


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

Date: Sun, 11 Jul 2004 11:41:42 GMT
From: "Julia De Silva" <jds@atavailcheck.com>
Subject: Re: looping through array
Message-Id: <WH9Ic.40475$Cr5.38126@fe2.news.blueyonder.co.uk>

> Hi all,
> this is trivvial question but how do you compare existense of elements
intwo
> arrays?, that is I want to compare two arrays and check the existense of
> the first array's elements in the second array,
>
> one line of code if possible...
>
> any advice much appreciated, thank you.
> /G
> --
> www.gh-webinteractive.com
>

Is that a FAQ or What !! perlfaq4 I think





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

Date: 11 Jul 2004 11:45:30 GMT
From: Abigail <abigail@abigail.nl>
Subject: Re: looping through array
Message-Id: <slrncf2a2q.4g9.abigail@alexandra.abigail.nl>

svenne (bobsmith@[) wrote on MMMCMLXVII September MCMXCIII in
<URL:news:Vr9Ic.2902$wV2.2361@reader1.news.jippii.net>:
;;  Hi all,
;;  this is trivvial question but how do you compare existense of elements intwo
;;  arrays?, that is I want to compare two arrays and check the existense of
;;  the first array's elements in the second array, 
;;  
;;  one line of code if possible...

$ perldoc -q intersection.


Abigail
-- 
BEGIN {$^H {join "" => ("a" .. "z") [8, 13, 19, 4, 6, 4, 17]} = sub
           {["", "Just ", "another ", "Perl ", "Hacker\n"] -> [shift]};
       $^H = hex join "" => reverse map {int ($_ / 2)} 0 .. 4}
print 1, 2, 3, 4;


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

Date: 11 Jul 2004 10:29:27 -0700
From: dan_yuan@trendmicro.com (Dan)
Subject: Re: Negation of RegEx
Message-Id: <4c135583.0407110929.7430e284@posting.google.com>

Tad McClellan <tadmc@augustmail.com> wrote in message news:<slrncf0k7s.f16.tadmc@magna.augustmail.com>...
> Dan <dan_yuan@trendmicro.com> wrote:
> 
> [ Please learn (and then use) the proper form for a followup posting.
>   Soon! 
> ]
> > can't be any other formats. :-(
> 
> 
> Why can't it be in any other format?
> 
> 
> 
> [ snip yet more TOFU. Sheesh! ]

The negation should be right in the boundary "/Negation of RegEx/".
Do you have any solution for that?

Thanks

Dan


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

Date: 11 Jul 2004 18:14:17 +0100
From: Brian McCauley <nobull@mail.com>
Subject: Re: Regexp substitution problem - suggestions?
Message-Id: <u9llhq1n6e.fsf@wcl-l.bham.ac.uk>

"A. Sinan Unur" <1usa@llenroc.ude> writes:
                              ^^^

Is the TLD "ude" reserved as one that will never be instanciated?  I
don't recall any RFC to that effect.

> You are posting email unmunged addresses from domain.com to a newsgroup for 
> spambots to harvest. I doubt you own the domain. IMNSHO, you will be 
> responsible for a lot of the future spam received at domain.com. If I were 
> the administrator of that site, I would complain loudly to your ISP.
> 
> If you want to use an example, try something like domain.tld. That would be 
> responsible.

Is the TLD "tld" reserved as one that will never be instanciated?  I
don't recall any RFC to that effect.

If you want an example domain that will never clash with a real domain
then please use a suffix defined for that purpose like ".invalid" or
".example.com".

-- 
     \\   ( )
  .  _\\__[oo
 .__/  \\ /\@
 .  l___\\
  # ll  l\\
 ###LL  LL\\


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

Date: 11 Jul 2004 17:39:07 GMT
From: "A. Sinan Unur" <1usa@llenroc.ude.invalid>
Subject: Re: Regexp substitution problem - suggestions?
Message-Id: <Xns95238AE039F71asu1cornelledu@132.236.56.8>

Brian McCauley <nobull@mail.com> wrote in
news:u9llhq1n6e.fsf@wcl-l.bham.ac.uk: 

> "A. Sinan Unur" <1usa@llenroc.ude> writes:
>                               ^^^
> Is the TLD "ude" reserved as one that will never be instanciated?  I
> don't recall any RFC to that effect.

 ...

>> If you want to use an example, try something like domain.tld. That
>> would be responsible.
> 
> Is the TLD "tld" reserved as one that will never be instanciated?  I
> don't recall any RFC to that effect.

Point taken.

-- 
A. Sinan Unur
1usa@llenroc.ude.invalid 
(remove '.invalid' and reverse each component for email address)


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

Date: 11 Jul 2004 09:12:26 -0700
From: jl_post@hotmail.com (J. Romano)
Subject: Re: Using scalar() on function return values
Message-Id: <b893f5d4.0407110812.49f5ac07@posting.google.com>

Joe Smith <Joe.Smith@inwap.com> wrote in message news:<17PGc.38208$IQ4.25974@attbi_s02>...
> 
>     return scalar('red', 'green', 'blue', @array);
> is the same as
>     return (scalar('red'), scalar('green'), scalar('blue'), scalar(@array));
> which in this case is
>     return (scalar('red'), scalar('green'), scalar('blue'), 3);

   Thanks.  That explains it well (you're the first to explain it to me that way).

   Thank-you for all your responses.

   -- Jean-Luc


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

Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>


Administrivia:

#The Perl-Users Digest is a retransmission of the USENET newsgroup
#comp.lang.perl.misc.  For subscription or unsubscription requests, send
#the single line:
#
#	subscribe perl-users
#or:
#	unsubscribe perl-users
#
#to almanac@ruby.oce.orst.edu.  

NOTE: due to the current flood of worm email banging on ruby, the smtp
server on ruby has been shut off until further notice. 

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

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

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


------------------------------
End of Perl-Users Digest V10 Issue 6791
***************************************


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