[24718] in Perl-Users-Digest

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

Perl-Users Digest, Issue: 6873 Volume: 10

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Aug 17 03:06:00 2004

Date: Tue, 17 Aug 2004 00:05:08 -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           Tue, 17 Aug 2004     Volume: 10 Number: 6873

Today's topics:
    Re: an approach <gnari@simnet.is>
        cpan update: 106 installed modules have no parseable ve <s_kelem@pacbell.net>
    Re: Earthquake forecasting program   Aug. 16, 2004 <matthew.garrish@sympatico.ca>
    Re: Earthquake forecasting program   Aug. 16, 2004 <edgrsprj@ix.netcom.com>
    Re: Earthquake forecasting program   Aug. 16, 2004 <edgrsprj@ix.netcom.com>
        Forcing Array Context (Peter Kay)
    Re: Forcing Array Context <1usa@llenroc.ude.invalid>
    Re: Forcing Array Context <mritty@gmail.com>
        How to turn a number into graphics? <SaveWorldFromAids@alexa.com>
    Re: IPC::Shareable exceptionally slow on large segs <admin@asarian-host.net>
    Re: Materializing an indirect sort using only swap <pinyaj@rpi.edu>
    Re: Materializing an indirect sort using only swap ctcgag@hotmail.com
        Module to filter HTML <corleone@godfather.com>
        My own handy Pocket Reference notes (David Filmer)
    Re: My own handy Pocket Reference notes <notvalid@email.com>
    Re: One liner for renaming files <tadmc@augustmail.com>
    Re: One liner for renaming files (Charles DeRykus)
    Re: One liner for renaming files <parv_@yahooWhereElse.com>
    Re: Parsing a text file into an array <tadmc@augustmail.com>
    Re: Placeholder in an sql query (dn_perl@hotmail.com)
    Re: Search/Replace in CSV files <bmb@ginger.libs.uga.edu>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

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

Date: Mon, 16 Aug 2004 22:14:56 -0000
From: "gnari" <gnari@simnet.is>
Subject: Re: an approach
Message-Id: <cfrbh2$mq5$1@news.simnet.is>

"db2guy" <db2boom@yahoo.com> wrote in message
news:ca559432.0408161103.24304688@posting.google.com...
> i am working on db2 and need a perl script to delete data from a
> table. There is a column in that table X lets say Xdate. Now i want to
> keep only 90 days of data and delete everything else. The Xdate is in
> timestamp format so its creating problems for me. ex
> 2004-03-31-00.00.00 so when i do current timestamp - 90 days the
> problem is coming with time part of timestamp.
> Can anyone suggest me a way.

I'll assume you know about DBI
I do not know about DB2's date functions, but surely there are
some that return the date part of a datestamp, or you can cast
(current day - 90 days) as timestamp or something.
In any case, surely you can do something like
    $sth=$dbh->do("delete from foo where Xdate < 2004-05-16-00.00.00");


> Also how can i put this values
> db2 "select count(*) from tableX" into a variable say $DD...
> any suggestion will be appriciated thanks...

oh. maybe you do not know about DBI.
take a look at cpan.org

you will need the modules DBI and DBD::DB2

gnari





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

Date: Tue, 17 Aug 2004 00:38:27 GMT
From: Steve Kelem <s_kelem@pacbell.net>
Subject: cpan update: 106 installed modules have no parseable version number
Message-Id: <7scUc.6943$4p1.4676@newssvr29.news.prodigy.com>

When I run CPAN.pm and type the option "r" (reinstall recommendations),
I get the message

106 installed modules have no parseable version number

Why so many modules without version numbers?
CPAN.pm has made module maintenance SOOOOOO easy, yet some modules can't 
be easily updated without parsable version numbers.

Steve Kelem


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

Date: Mon, 16 Aug 2004 19:31:11 -0400
From: "Matt Garrish" <matthew.garrish@sympatico.ca>
Subject: Re: Earthquake forecasting program   Aug. 16, 2004
Message-Id: <ZsbUc.9895$Tr.505000@news20.bellglobal.com>


"edgrsprj" <edgrsprj@ix.netcom.com> wrote in message
news:0f1Uc.23551$nx2.17009@newsread2.news.atl.earthlink.net...
> August 16, 2004   Posted to sci.geo.earthquakes and other Newsgroups
>
> The following Web page contains
> instructions for how to obtain a free copy of a Perl compiler:
>
> http://www.freewebz.com/eq-forecasting/Perl.html
>

From said page:

<quote>
Start An External Program Running From Within A Perl Program
If the "exec" version of the run command is used then the external program
begins running and the Perl program immediately ends.
</quote>

Why do you persist in publishing your inept rerendering of the Perl
documentation online?

Matt




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

Date: Tue, 17 Aug 2004 06:11:08 GMT
From: "edgrsprj" <edgrsprj@ix.netcom.com>
Subject: Re: Earthquake forecasting program   Aug. 16, 2004
Message-Id: <0khUc.50$2L3.39@newsread3.news.atl.earthlink.net>


"Matt Garrish" <matthew.garrish@sympatico.ca> wrote in message
news:ZsbUc.9895$Tr.505000@news20.bellglobal.com...
>

> Why do you persist in publishing your inept rerendering of the Perl
> documentation online?
>

August 17, 2004



Hi Matt,



This is the reason that information page is there.



If you want to use Perl to do some very basic things such as read two
numbers from the keyboard or a data file, multiply them together, and then
display the results on the computer screen and store them in a file then you
can use those commands in that manner to do that.  And that is exactly what
I have done with that earthquake forecasting computer program I created.
The code it contains would probably cause professional computer programmers
to have nightmares.  But it works.  And it is or perhaps it will be
providing people around the world with what I believe is vitally important
information which could represent the difference between life and death.



There is no other choice here.  Perl is the only program that I know of
which has the necessary power, which is actively supported, and which
researchers around the world can obtain for free.  And I believe that with a
few adjustments my program should run on any computer which is can run a
Perl program.



I don't have time to become an expert Perl programmer.  And neither do the
people with whom I am talking and working.  So we are trying to get along as
best as possible with what is available.



Now that my program is operational and it appears to be producing good
result we can hopefully start getting actual programmers involved with
development efforts.  People are interested in helping.  But the immediate
problem is that there is no organized group for getting the work done.  And
at the moment I myself don't have enough free time to do both basic research
and direct the activities of the volunteer programmers.



It appears to me that the alternative is to simply say, "Earthquakes can't
be predicted" and just let people everywhere continue to die when they
occur.  And I personally feel that this really is the choice here.  We are
quite literally facing a life and death situation.



Finally, something that I would like to see built into some future version
of Perl is a subset of very simple commands which would let even amateur
computer programmers use it to do basic things such as read information from
files.  That command subset would make it something like GW-BASIC.  People
could begin using it immediately.  And as they became more familiar with it
they could develop an understanding of the more complex commands.



So, a fundamental question regarding Perl might be, "Is it intended to be
for only expert computer programmers?  Or is it intended to be a highly
versatile language which even beginning programmers can use?"



You would probably know more about that than I do.






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

Date: Tue, 17 Aug 2004 06:55:50 GMT
From: "edgrsprj" <edgrsprj@ix.netcom.com>
Subject: Re: Earthquake forecasting program   Aug. 16, 2004
Message-Id: <WZhUc.60$2L3.30@newsread3.news.atl.earthlink.net>


"Jaxtraw" <jaxtraw@nospamnobigfoot.com> wrote in message
news:1092684544.19111.0@ersa.uk.clara.net...
> "edgrsprj" <edgrsprj@ix.netcom.com> wrote in message
> news:0f1Uc.23551$nx2.17009@newsread2.news.atl.earthlink.net...
> > August 16, 2004   Posted to sci.geo.earthquakes and other Newsgroups

>
> Intriguing, but it seems to me you should test also for false negatives.
> ...

August 17, 2004

Hi Ian,  Thanks for the comments.

At the moment this what might be described as "Any port in the storm
technology."  That means that we have a desperate situation where
earthquakes are claiming lives without anything to stop that from happening.
More than 25,000 people reportedly perished last December in Iran from an
unexpected earthquake.  And the immediate goal is to find anything at all
which can help.

I know of at least two promising looking technologies which are being used
in China.  But each of the detector units runs something like $10,000 U.S.
You need multiple units to cover a given area plus all of the support
personnel.  And they still apparently miss an unacceptably high percentage
of the destructive earthquakes.

One of the reasons that my program looks so attractive at the moment is the
fact that it appears to be highly selective for earthquakes which will occur
near cities around the world.  My present theory is that this has to do with
the dense collection of electrical wires and metal water pipes in highly
populated areas.  They are acting like antennas for the EM signals which are
being detected.  Are they sending out pulses?  Or are they acting like
"sinks" or "short circuits" for an already existing signal and producing
what might be called negative pulses where the signal abruptly ceases for 10
seconds?  I don't know the answer to that question.  And in years of
searching I haven't been able to locate any research groups interested in
determining what might be taking place.

Another reason it looks so attractive is the fact that to get it to work all
you need is a reasonably powerful personal computer, some EM signal data,
and a catalogue of past earthquakes for its database.  And I believe that
usable EM signal data should be available for free from sources around the
world.  People could probably use my EM signal data if they could not find
their own sources.

So in theory, a single person could generate forecasts for a good percentage
of the destructive earthquakes which are occurring around the world.  And
with that in mind, consider how well the program might work if there were
research groups in every country using it?  Also, I am making it available
to people around the world to use for free.

It can work like this:

Say you are a government earthquake forecaster in Taiwan.  What you would do
is keep track of the final rating numbers for Taiwan area earthquakes each
time a program run is completed.  If one or more got into the 90 and above
range then they would be watched more carefully.  If several started heading
towards a 100 rating then you would begin watching those areas for other
signs of an approaching earthquake.  Individual governments have to do that
themselves.  I myself can't keep track of everyone's earthquakes.  And I
have said that to government and disaster mitigation personnel around the
world.

Right now what the program needs is for people to do more data evaluations
and then some fine tuning.  It can take me a full hour to complete a single
run on my moderately powerful personal computer.  So, that means some
computer programmers and statistics experts.  And there are people who are
interested in helping with that.  I talk with them on a regular basis.  But
such an effort would really require an organized research group.  I myself
can't manage the research activities of a group of programmers and
statistics experts.  Unfortunately, groups that I have contacted so far
regarding taking charge of such an effort have not been interested.  And
what a strange situation that is!  Some of those groups could be decimated
by an unexpected earthquake.  You would think that they would jump at the
chance to have some technology which might save their hides, especially when
it is essentially free.




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

Date: 16 Aug 2004 15:10:59 -0700
From: peterkayatwork@yahoo.com (Peter Kay)
Subject: Forcing Array Context
Message-Id: <3081c9ae.0408161410.16143c88@posting.google.com>

I want to pass in arguments to a subroutine via an array or list. 
Seems simple enough, right?  Well, no, because the array keeps getting
kicked into scalar context.  An example perl script is provided:

Any thoughts?
Thanks,
--Peter

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

#!/usr/bin/perl -w
use strict;

sub do_it ($$@);

my @args=("a","b","c");

do_it( "a", "b", @args );  #works
do_it( @args );  # Doesn't work:
# Not enough arguments for main::do_it at g.pl line 9, near "@args )"
# Execution of test.pl aborted due to compilation errors.


sub do_it ($$@)
{
    my ($a, $b, @c) = @_;
    print("Loaded $a, $b, others of @c\n");
}


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

Date: 16 Aug 2004 22:23:16 GMT
From: "A. Sinan Unur" <1usa@llenroc.ude.invalid>
Subject: Re: Forcing Array Context
Message-Id: <Xns9547BB0D83430asu1cornelledu@132.236.56.8>

peterkayatwork@yahoo.com (Peter Kay) wrote in 
news:3081c9ae.0408161410.16143c88@posting.google.com:

> I want to pass in arguments to a subroutine via an array or list. 
> Seems simple enough, right?  Well, no, because the array keeps getting
> kicked into scalar context.  An example perl script is provided:
> 
> Any thoughts?

I don't get it. You specify prototype and then complain when that prototype 
is obeyed. Either the prototype is wrong or the way you call the sub.

 ...

> #!/usr/bin/perl -w
> use strict;
> 
> sub do_it ($$@);
> 
> my @args=("a","b","c");

Whitespace is not a scarce commodity.
 
> do_it( "a", "b", @args );  #works
> do_it( @args );  # Doesn't work:
> # Not enough arguments for main::do_it at g.pl line 9, near "@args )"
> # Execution of test.pl aborted due to compilation errors.

Actually, that is working. The fact that it does not do what you want is 
immaterial.

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



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

Date: Mon, 16 Aug 2004 19:23:21 -0400
From: Paul Lalli <mritty@gmail.com>
Subject: Re: Forcing Array Context
Message-Id: <20040816192126.O2996@barbara.cs.rpi.edu>

On Mon, 16 Aug 2004, Peter Kay wrote:

> I want to pass in arguments to a subroutine via an array or list.
> Seems simple enough, right?  Well, no, because the array keeps getting
> kicked into scalar context.  An example perl script is provided:
>
> Any thoughts?
> Thanks,
> --Peter
>
> ------------------------------
>
> #!/usr/bin/perl -w
> use strict;
>
> sub do_it ($$@);
>
> my @args=("a","b","c");
>
> do_it( "a", "b", @args );  #works
> do_it( @args );  # Doesn't work:
> # Not enough arguments for main::do_it at g.pl line 9, near "@args )"
> # Execution of test.pl aborted due to compilation errors.
>
>
> sub do_it ($$@)
> {
>     my ($a, $b, @c) = @_;
>     print("Loaded $a, $b, others of @c\n");
> }


You say you want to pass in parameters via an array, but you very
specifically define the subroutine to only allow two scalars followed by a
list.  So is your description wrong, or do you just not understand why
you're using a prototype?

To put it another way - Perl's doing both exactly what it's supposed to
do, and exactly what you told it to.   If that's not what you want, stop
telling it to do that.

Paul Lalli


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

Date: Tue, 17 Aug 2004 05:15:43 GMT
From: "http://links.i6networks.com" <SaveWorldFromAids@alexa.com>
Subject: How to turn a number into graphics?
Message-Id: <3wgUc.305$E7T1.33@news04.bloor.is.net.cable.rogers.com>

Any free scripting turning numbers into a graph?

Similar to an image/graphics counter. PHP or Perl




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

Date: Tue, 17 Aug 2004 06:50:50 +0200
From: "Mark" <admin@asarian-host.net>
Subject: Re: IPC::Shareable exceptionally slow on large segs
Message-Id: <V9Odnb86S8UpE7zcRVn-hQ@giganews.com>

Anno Siegel wrote:

>> I have been experimenting with IPC::Shareable 0.60 on FreeBSD
>> 4.10-p2, using perl 5.8.5. Everything works great... for small
>> memory segments, that is. With a default memory segment size of 64K,
>> things fly.
>>
>> If I increase the requested memory segment to a more useable size,
>> say 1M, reading/writing to the tied hash suddenly takes considerably
>> longer (in fact, it seems the lookup/write time is directly
>> proportionate to the increase in memory size). What does that mean?
>> In practice, it means a single hash lookup on a 1M segment takes
>> about 1/2 second! Which is, IHMO, indeed exceptionally long.
>>
>> I have 32M free shared memory, mapped to physical memory exclusively
>> (unswappable). So that cannot be the cause. Does anyone have any
>> ideas as to why this occurs?
>
> From a glance at IPC::Shareable it seems that your 32 MB of hash is
> potentially expanded ("thawed") for every access.  That would explain
> some delay.
>
> At the risk of appearing old-fashioned, let me add that using shared
> memory directly for storing mass data appears as a huge waste of
> resources. Conceptually, shared memory is the most basic of IPC
> mechanisms. It used to be used as sparingly as possible to implement
> other mechanisms that protect larger areas of memory.

Thank you for your reply.

I use the large hash for DNSBL cache lookups in a threaded environment.
Using a shared hash was causing quite a bit of overhead.

Just in case anyone is interested, using IPC::Shareable, writing 21960
entries to the hash cost:

shmem: 5972 wallclock secs (3836.48 usr + 2106.69 sys = 5943.17 CPU)

Which comes down to 0.271 seconds per write (my half-a-second estimate was a
bit exaggerated; still, this takes a very long time).

I never really used IPC::ShareLite before, as it did not have a neat tied
interface. However, I recently found a brand new module, Tie::ShareLite (03
Aug 2004), which makes for an in-drop replacement for IPC::Shareable (it
only does hashes, though). It is faster (0.16 seconds per write for 21960
entries). Plus, IPC::ShareLite has the nice quality of allocating only 65536
bytes per segment, and then automagically adds a new chunk if more is
needed. All fully transparent to the user-interface, of course.

- Mark




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

Date: Mon, 16 Aug 2004 18:10:51 -0400
From: Jeff 'japhy' Pinyan <pinyaj@rpi.edu>
Subject: Re: Materializing an indirect sort using only swap
Message-Id: <Pine.SGI.3.96.1040816175753.1331700B-100000@vcmr-64.server.rpi.edu>

On 16 Aug 2004 ctcgag@hotmail.com wrote:

>my @idx = "dummy", sort {$x[$a]<=>$x[$b]} 0..$#x;
>
>Now, I merely have to use @idx as a translation table so that I can access
>sub-objects as if they were sorted.  Works great for the most part, but
>I've reached a point where that isn't good enough and I need to materialize
>the sort into the object itself.  So I'm trying to use the transformation
>implied in @idx to apply a proper series of $o->swap($foo,$bar) operations
>to put the sub-objects in order.

So you basically want to take an array like

  ('this', 'little', 'piggie', 'went', 'to', 'market')

and use only a swap(@array, $x, $y) function to produce the same array as
if the indices were in the order (3,5,1,2,0,4)?

That is:

  my @array = qw( this little piggie went to market );
  my @order = qw( 3 5 1 2 0 4 );
  my @new = multi_swap(\@array, \@order);
  # expect: (went market little piggie this to)

Where the multi_swap() function applies a series of swap()s... is that
right?  If so, let me know... I think I can work up an algorithm.

--
Jeff "japhy" Pinyan         %  How can we ever be the sold short or
RPI Acacia Brother #734     %  the cheated, we who for every service
RPI Corporation Secretary   %  have long ago been overpaid?
http://japhy.perlmonk.org/  %  
http://www.perlmonks.org/   %    -- Meister Eckhart




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

Date: 16 Aug 2004 23:05:57 GMT
From: ctcgag@hotmail.com
Subject: Re: Materializing an indirect sort using only swap
Message-Id: <20040816190557.180$0x@newsreader.com>

Jeff 'japhy' Pinyan <pinyaj@rpi.edu> wrote:
> On 16 Aug 2004 ctcgag@hotmail.com wrote:
>
> >my @idx = "dummy", sort {$x[$a]<=>$x[$b]} 0..$#x;
> >
> >Now, I merely have to use @idx as a translation table so that I can
> >access sub-objects as if they were sorted.  Works great for the most
> >part, but I've reached a point where that isn't good enough and I need
> >to materialize the sort into the object itself.  So I'm trying to use
> >the transformation implied in @idx to apply a proper series of
> >$o->swap($foo,$bar) operations to put the sub-objects in order.
>
> So you basically want to take an array like
>
>   ('this', 'little', 'piggie', 'went', 'to', 'market')
>
> and use only a swap(@array, $x, $y) function to produce the same array as
> if the indices were in the order (3,5,1,2,0,4)?
>
> That is:
>
>   my @array = qw( this little piggie went to market );
>   my @order = qw( 3 5 1 2 0 4 );
>   my @new = multi_swap(\@array, \@order);
>   # expect: (went market little piggie this to)
>
> Where the multi_swap() function applies a series of swap()s... is that
> right?  If so, let me know... I think I can work up an algorithm.


Yes, precisely correct.

Xho

-- 
-------------------- http://NewsReader.Com/ --------------------
Usenet Newsgroup Service                        $9.95/Month 30GB


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

Date: Tue, 17 Aug 2004 11:48:36 +0900
From: Vito Corleone <corleone@godfather.com>
Subject: Module to filter HTML
Message-Id: <20040817114836.741d9e28.corleone@godfather.com>

Hi,
I am looking for module to filter HTML input from user. It should allow
<b> <i> <img> and some other tags, and remove the evil tags. I found
HTML::Sanitizer, but the last update is August 2003. Is there any other
alternative? Or is it ok to use HTML::Sanitizer? Thank you very much.

--Vito


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

Date: 16 Aug 2004 16:45:23 -0700
From: IneverReadAnythingSentToMe@hotmail.com (David Filmer)
Subject: My own handy Pocket Reference notes
Message-Id: <e4c916dd.0408161545.4dd376ac@posting.google.com>

In a previous thread
(http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=e4c916dd.0408111652.3099c07c%40posting.google.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3De4c916dd.0408111652.3099c07c%2540posting.google.com)
I posted a transcription of little hints/shortcuts that I have written
inside the covers of my Perl Pocket Reference over the years. A number
of helpful people have kindly provided corrections/comments (thanks!).
Although nobody suggested any brand-new items, some comments led me to
include alternate approaches for some items and some additional
content not previously covered.

I have made some effort to group similar items (some could fall into
multiple categories). As before, the notes are 70-col wide (displays
nice Google Groups, which is the only usenet access for many people
behind corp. firewalls). If printed in 6pt Courier it's 9cm wide -
fits nicely inside the cover of a Pocket Reference.

These are mainly syntax HINTS. In some cases the examples are so
trivial that other methods would be preferred. And, of course, there
are often many ways to
do things. This is not a HOWTO.

So here are my corrected/modified notes, provided here in the hope
that someone else might find them useful:

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
============================================= VARIABLE MANIPUTATION ==
Instead of: $a = $b; $a = s/foo/bar/; ($a as a modified version of $b)
   ($a = $b) =~ s/foo/bar/;
======================================================================
Instead of: $a =~ /foo(.*)/; $b = $1; ($a as a substring of $b)
   ($b) = ($a =~ /foo(.*)/);
======================================================================
To strip leading or trailing spaces:
   $foo =~ s/^\s+//;   $foo =~ s/\s+$//;
OR s/^\s+//, s/\s+$// for $foo;       # To do both sides at once
======================================================================
To set a variable but ONLY if it is currently undefined/zero/null:
   $foo ||= 'bar';
======================================================================
To set a variable to the greater (larger) of two choices:
   $var = ($a > $b) ? $a : $b;
Similarly, to (for example) print if a number is even or odd:
   print "The number is ", ($num % 2) ? "odd" : "even";  # % is modulo
======================================================================
To round off a number to "n" decimal places (or use Number::Format)
   sprintf ("%.nf", $foo);   #replace "n" with a variable or constant
======================================================================
To strip the path from a filename (such as $0) w/o File::Basename:
   print $0 =~ m{([^/]*)$};   #or $0 =~ (/^.*\/(.*)/)[0]
======================================================================
To embed a variable in a variable name  (causes the earth to explode):
   $foo = "foo"; print ${"${foo}bar"}; #same as ${'foobar'} or $foobar
#symbolic reference-bad idea. Try to use real ref or hash data struct
======================================================================
To generate a random integer between 0 and 10 (inclusive):
   $foo = int rand(11); #or int rand(10)+1  between 1 and 10 inclusive
======================================================================
To replace $foo with $bar across an array
   @list2 = map s/$foo/$bar/, @list;    #or map {s/$foo/$bar/} @list;
   print s/$foo/$bar/ for @list         #ie, void context
   map {$_  =~ s/$foo/$bar/g} @LIST     #changes @LIST
======================================================================
To sort an array numerically (instead of Perl default alpha sort):
   @sorted = sort { $a <=> $b } @unsorted;    #Perl Cookbook 1ed p115

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
======================================================= SUBROUTINE  ==
To pass a filehandle (FH) the proper way, (for example with CGI.pm):
   $foo = new CGI (\*FH);
======================================================================
To pass a only single hash to a subroutine (without using references):
   &MySubroutine(%foo);   #call the sub and pass it a hash directly
   sub MySubroutine { my %bar = @_; ...etc... }
======================================================================
To pass a hash from a subroutine:
   %foo = my_sub();
   sub my_sub {$bar{'candy'}='chocolate'; return %bar; }

OR %foo = %{&MySubroutine()};
   sub MySubroutine { my $bar{'candy'}='chocolate'; return \%bar; }  
======================================================================
Subroutine Prototypes. SYNTAX: if_defined_this_way  #call_this_way
   sub foo($)    #foo $bar1           |  sub foo(\@)  #foo @bar
   sub foo($$)   #foo $bar1 $bar2     |  sub foo(\%)  #foo %{$hashref}
   sub foo($$;$) #foo $b1, $b2, $opt  |  sub foo(*)   #foo *bar
   sub foo(@)    #foo $b1,$b2,$b3     |  sub ()       #foo
======================================================================
To pass by reference to/from subroutine:
   @a = (1..3); @b = (4..6);
   ($s_ref, $p_ref) = do_math (\@a, \@b); #sum/multply mbrs of @a & @b
   print "Sum: @{[join ',',@{$s_ref}]} Prod: @{[join ',',@$p_ref]}\n";

   sub do_math {  #add and multiply values of two lists (no err chk!)
      while(@{$_[0]}) {$n1=pop @{$_[0]}; $n2 = pop @{$_[1]};
         unshift @sum, $n1 + $n2; unshift @product, $n1 * $n2; }
      return \@sum, \@product;
   }

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
============================================================ OUTPUT ==
To redirect STDOUT to a file (or any filehandle to another filehandle)
   *STDOUT = *OUT;    #great for debugging when output usually to file
======================================================================
To have output go through pager program:
   $pager = $ENV{'PAGER'} || '/usr/bin/less';  #make SURE pager is OK
   open (STDOUT, "| $pager");   # terminal output one page at a time!
======================================================================
To enable auto-flushing of output (ie, simulate no buffering):
   select(STDERR); $| = 1; select(STDOUT); $| = 1;
======================================================================
Instead of:  $answer = $var1 . func() . $var2;   #concat together
   $answer = "$var1 @{[ LIST EXPR ]} $var2"; #force 'scalar' if req'd
(ie, $foo = "uppercase"; print "here is @{[uc $foo]} text";)
#example too trivial; for this would use "Here is \U$foo\E text"   
======================================================================
To print $number, but print a zero if the variable is undefined:
   print $number || '0';
======================================================================
To pad text with spaces (or zeros) to make string "n" chars in length:
   padding on RIGHT:  sprintf("%-ns", $foo);
   padding on LEFT:   sprintf("%ns",  $foo);   #or ("%0nd") for zeros
======================================================================
To indent a "here document" in code but not in output:
   ($var = <<'   HERE') =~ s/^\s+//gm;   #allow HERE target to indent!
      Lorem ipsum                        #Perl Cookbook 1ed p 23
      dolor sit amet
   HERE
======================================================================
To print a hash in a prettified way:
   print map { "$_\t=>\t$hash{$_}\n" } sort keys %hash;
   
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
============================================================== MISC ==
To simulate UN*X `grep -v`
   grep (!/foo/, @foo);   #or (!/foo/i, @foo) to simulate `grep -vi`
======================================================================
To simulate UN*X `uniq` (create @uniq w/distinct members of @orig)
   %seen=(); @uniq = grep{! $seen{$_}++} @orig;
======================================================================
Schwartzian Transform: For example, to sort /etc/passwd file by fields
   print map { $_->[0] }             #Randal (one l) Schwartz Rocks!!!
      sort {    $a->[1] <=> $b->[1]  #numerically sort first  by gid
             || $a->[2] <=> $b->[2]  #numerically sort second by uid
             || $a->[3] cmp $b->[3]  #alphabetic sort by loginID last
      } map { [ $_, (split /:/)[3,2,0] ] } `cat /etc/passwd`;

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
========================================================= DATE/TIME==
To print current date in format "YYYY-MM-DD" (ISO 8601), ie SQL format
   ($day, $month, $year) = (localtime)[3,4,5];  #no modules
      printf("%04d-%02d-%02d", $year+1900, $month+1, $day);
OR printf("%04d-%02d-%02d",
       sub {($_[5]+1900,$_[4]+1,$_[3])}->(localtime)); #no temp vars
OR use POSIX qw/strftime/; print strftime "%Y-%m-%d", localtime;
OR use Time::localtime; $tm = localtime; 
    printf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);
OR use Date::Manip; print UnixDate(scalar localtime, "%Y-%m-%d");
======================================================================
To get the mtime (lmod) of a file:
   $mtime = (stat $file)[9];  #epoch time (1065381040). [8] = atime.
OR $mtime = localtime ((stat ($file))[9]); # Wed Aug 11 12:07:44 2004
OR $mtime = sprintf("%04d-%02d-%02d",      #ie, YYYY-MM-DD w/o modules
      sub{($_[5]+1900,$_[4]+1,$_[3])}->(localtime((stat($file))[9])));
======================================================================
To set file mtime (w/o File::Touch)(UTC: timegen instead of timelocal)
   use Time::Local;
   $mtime = timelocal($sec, $min, $hours, $mday, $month, $year);
   utime( (stat($file)[9]), $mtime, $file ); #must include atime

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
============================================ MULTI-DIMENSIONAL ARRAY==
ARRAY OF ARRAYS (ie, $cars[0][1] eq 'yellow';ALT SYNTAX: $car[0]->[1])
   @cars =([qw/red yellow green/],[qw/ford chevy/],[qw/coupe sedan/]);
HASH OF ARRAYS  (ie, $car{'col'}[1] eq 'yellow')
   %cars = (col=>[qw/red yellow green/],
            make=>[qw/ford chevy/],body=>[qw/coupe sedan/]);
HASH OF HASHES (ie, $org{sales}{boss} eq 'Sue')
   %org = (sales=>{boss=>'Sue', peon=>'Rob'},
           mailroom=>{boss=>'Joe', peon => 'Jane'});
ARRAY OF HASHES (ie, $org[0]{boss} eq 'Sue'; $org[1]{peon} eq 'Jane')
   @org = ({boss=>'Sue', peon=>'Rob'}, {boss=>'Joe', peon => 'Jane'});

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=========================================================== IO::ALL ==
IO::All module is great! Instead of:
   open (IN,'<','./stuff')||die $!;local $/;my $stuff = <IN>;close IN;
DO use IO::All; my $stuff < io"./stuff";   #let IO::All do the work!

Other kewl things (per perldoc)
  #FILES
    $io = io 'file.txt';                # Create a new IO::All object 
    $contents = $io->all;               # read everything (or ->slurp)
    $contents = join '', $io->getlines; # Join the separate lines
    $content > io('file.txt');          # Print to file(>> for append)
    @lines  = io('file.txt')->chomp->slurp;     # Chomp as you slurp
    @chunks = io('file.txt')->separator('xxx')->slurp; #alt record sep
  #DIRS
    $io = io('my/directory/');          # Create new DIRECTORY object
    @contents = $io->all;               # Get all contents of dir
    @contents = @$io;                   # Directory as an array
    @contents = values %$io;            # Directory as a hash
  #STAT
    printf "%s %s %s\n",                # Print name, uid and size of 
      $_->name, $_->uid, $_->size       # contents of current dir
        for io('.')->all;
    print "$_\n" for sort               # Use mtime method to sort all
      {$b->mtime <=> $a->mtime}         # files under current dir
        io('.')->All_Files;             # by recent modification time.
  #EXTERNAL
    io("myfile") > io->("ftp://store.org");     # Upload file via ftp
    $html < io->http("www.google.com");         # Grab a web page
    io('mailto:worst@enemy.net')->print($spam); # Email a "friend"
======================================================================


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

Date: Tue, 17 Aug 2004 05:38:40 GMT
From: Ala Qumsieh <notvalid@email.com>
Subject: Re: My own handy Pocket Reference notes
Message-Id: <ARgUc.905$SR4.237@newssvr14.news.prodigy.com>

David Filmer wrote:

> To set a variable to the greater (larger) of two choices:
>    $var = ($a > $b) ? $a : $b;

I find this a bit more amusing, although less maintainable:

	$var = [$b => $a] -> [$b <= $a];

> To replace $foo with $bar across an array
>    print s/$foo/$bar/ for @list         #ie, void context

why print?

	s/$foo/$bar/ for @list;

--Ala



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

Date: Mon, 16 Aug 2004 17:48:03 -0500
From: Tad McClellan <tadmc@augustmail.com>
Subject: Re: One liner for renaming files
Message-Id: <slrnci2ed3.as8.tadmc@magna.augustmail.com>

D. Alvarado <laredotornado@zipmail.com> wrote:

>    I am looking for a one line command 


Why restrict it to one line?

If someone has a two-line solution, they should not post it?


> that I could run with perl to
> rename a group of files.  The desired outcome is
> 
> start          end
> -----          ---
> ctf_005.liv    ctf05cae002.liv
> ctf_006.liv    ctf05cae003.liv
> ctf_007.liv    ctf05cae004.liv
> ctf_008.liv    ctf05cae005.liv
> 
> and so on.
> 
> Any advice is greatly appreciated, - Dave


Get it working with many lines of code first, then pare it
down to one line. Post here if you get struck.

An example is not a specification. It would be helpful if you
described what transformation you want to have made...


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: Tue, 17 Aug 2004 00:27:55 GMT
From: ced@bcstec.ca.boeing.com (Charles DeRykus)
Subject: Re: One liner for renaming files
Message-Id: <I2KEMJ.Hq@news.boeing.com>

In article <9fe1f2ad.0408161310.1a09d7dc@posting.google.com>,
D. Alvarado <laredotornado@zipmail.com> wrote:
>Hello,
>   I am looking for a one line command that I could run with perl to
>rename a group of files.  The desired outcome is
>
>start          end
>-----          ---
>ctf_005.liv    ctf05cae002.liv
>ctf_006.liv    ctf05cae003.liv
>ctf_007.liv    ctf05cae004.liv
>ctf_008.liv    ctf05cae005.liv
>


perl -e 'for (@ARGV){($to=$_)=~s/_(\d+)/sprintf "05cae%03d",$1-3/e; \
          rename $_,$to or warn $!}' ctf_*.liv

People can go mad on the golf course though so you might want to
create a more general utility and save it to a file.  There are
simply too many things that go wrong with one-liners unless they're
simple.

hth,
--
Charles DeRykus


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

Date: Mon, 16 Aug 2004 20:53:55 -0500
From: parv <parv_@yahooWhereElse.com>
Subject: Re: One liner for renaming files
Message-Id: <slrnci2pda.3rn.parv_@localhost.holy.cow>

in message <9fe1f2ad.0408161310.1a09d7dc@posting.google.com>,
wrote D. Alvarado ...

>    I am looking for a one line command that I could run with perl to
> rename a group of files.  The desired outcome is
>
> start          end
> -----          ---
> ctf_005.liv    ctf05cae002.liv
> ctf_006.liv    ctf05cae003.liv
> ctf_007.liv    ctf05cae004.liv
> ctf_008.liv    ctf05cae005.liv
>
> and so on.

Following would be overkill many times over for you then...

  Efforts of some others...

    http://perlmonks.org/index.pl?node_id=303814
    http://perlmonks.org/index.pl?node_id=277174


  ...and to toot my own horn...

    Distribution:
      http://www103.pair.com/parv/comp/src/perl/sanename
      http://www103.pair.com/parv/comp/src/perl/dist/File-Name-Sanitize-1.01.tar.gz
      http://www103.pair.com/parv/comp/src/perl/dist/Parv-Util-1.10.tar.gz

    Pod:
      http://www103.pair.com/parv/comp/src/perl/pod/sanename.pod
      http://www103.pair.com/parv/comp/src/perl/pod/File-Name-Sanitize.pod
      http://www103.pair.com/parv/comp/src/perl/pod/Parv-Util-Compile.pod


  - parv

-- 
As nice it is to receive personal mail, too much sweetness causes
tooth decay.  Unless you have burning desire to contact me, do not do
away w/ WhereElse in the address for private communication.



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

Date: Mon, 16 Aug 2004 15:02:08 -0500
From: Tad McClellan <tadmc@augustmail.com>
Subject: Re: Parsing a text file into an array
Message-Id: <slrnci24m0.aiv.tadmc@magna.augustmail.com>

Scott <sroth1979@hotmail.com> wrote:

> I having a bit of trouble trying to parse...
                            ^^^^^^
                            ^^^^^^

> Does any one have some suggestions?


Show what you have tried and we will help you fix it.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas


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

Date: 16 Aug 2004 22:43:01 -0700
From: dn_perl@hotmail.com (dn_perl@hotmail.com)
Subject: Re: Placeholder in an sql query
Message-Id: <97314b5b.0408162143.2cd50109@posting.google.com>

I had written -
> I want to use placeholder to escape special characters directly
> via DBI while constructing an sql query.
> 

I am guessing now that the problem could be somehow associated with
a specific field named 'part' in a table. Is 'part' a reserved
word? But even that cannot be the case because without placeholder,
the query works just fine.

(I am using strict, but I tried to use warnings as well, as
per Mr Aursand's suggestion and got an error that warnings.pm
was not present in @INC. I will try to fix this problem tomorrow.)


The following code works properly :

=====================================
use vars qw($check_part $check_location) ;
 
$check_part = "clock" ;
$check_location = "room_1" ;
    # stmt X1 follows
my $dstmt = $dbh->prepare("select count(*) from inventory 
      where part = '$check_part' and loc = '$check_location'  ");  
$dstmt->execute() or die "sql call failed";   
my $num_entries = $dstmt->fetchrow() ;
$dstmt->finish ;
=====================================
I get correct value in $num_entries and it happens to be 1.


If I use placeholder for 'loc' field, I get the expected result.
my $dstmt = $dbh->prepare("select count(*) from inventory 
      where part = '$check_part' and loc = ?  ");  
$dstmt->execute($check_location) or die "sql call failed";   


But if I use placeholder for 'part' field, things go wrong.
my $dstmt = $dbh->prepare("select count(*) from inventory 
      where part = ? and loc = '$check_location'  ");  
$dstmt->execute($check_part) or die "sql call failed";   
my $num_entries = $dstmt->fetchrow() ;
      I get $num_entries = 0 instead of 1 .


Similarly, even where just one condition is being checked,
'part' field is giving problems.
    # the following works with placeholder
my $dstmt = $dbh->prepare("select count(*) from inventory 
      where loc = ?  ");  
    # the following does not work with placeholder
my $dstmt = $dbh->prepare("select count(*) from inventory 
      where part = ? ");  # (But this works without placeholder)


Please advise.


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

Date: Mon, 16 Aug 2004 20:34:19 -0400
From: Brad Baxter <bmb@ginger.libs.uga.edu>
Subject: Re: Search/Replace in CSV files
Message-Id: <Pine.A41.4.58.0408162006070.50406@ginger.libs.uga.edu>

On Mon, 16 Aug 2004, Doug Wells wrote:

> Hi-
> I seem to be drawing a complete blank, can anyone help? I have two CSV
> files. I want to look at file one and for each entry, if that entry
> appears in the second file remove it from the second file. So, in the
> end, i will have a new second csv file that has the first file items
> removed.

I wonder if CSV is a red herring.  When you say, 'if that entry appears in
the second file', do you really mean, 'if that LINE appears ...'  If so,
then you can ignore CSV altogether and just compare lines.  If you can
load the entire first file into a hash, then it's relatively simple to:

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

my %hash;
open F1, 'file1' or die $!;
open F2, 'file2' or die $!;
open F3, '>file3' or die $!;
map $hash{ $_ } = 1, <F1>;
map { print F3 unless $hash{ $_ } } <F2>;
rename 'file3', 'file2' or die $!;

__END__
file1:
abc
def
ghi

file2:
123
abc
456

file3 (new file2):
123
456


If not, then it's a different problem.  :-)

Regards,

Brad


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

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 6873
***************************************


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