Bob Showalter
Aug 27 2003, 11:58 AM
Vema Venkata wrote:
QUOTE |
Folks, Here the following xapipgm.pl is executed well when iam executing manualy, but when iam trying to set it thru corntab iam not able to execute
The crontab settings are as follows
1-59 * * * * . /home/paradigm/.profile; /proj/ahd02/CAisd/site/mods/scripts/xapipgm.pl /proj/ahd02/CAisd/site/mods/scripts/log/init/ahdxapi.log
The error iam getting is as follows
***************************** sh: log/init/ahdxapi.init.log: cannot create
|
This appears to be coming from the qx() line at the end of the script below.
You seem to be making assumptions about the current directory which are not
valid. Either use chdir() in your script to set the working directory, or
use a full path to your log file.
QUOTE |
*****************************
************************************************************** ******************************** #!/proj/ahd02/CAisd/ActivePerl-5.6.0.618/bin/perl #/usr/local/bin/perl $xapipgm = "srvtst26.pl"; $ret = qx ( pgrep -f srvtst26); if ($? eq 0){ $ret = qx(pgrep - f $xapipgm); print "AHD XAPI SERver ($xapipgm) Running with Process ID : $$"; } else { open F, ">> log/init/ahdxapi.init.log";
|
You don't check for errors here. I suspect this open is failing.
QUOTE |
print F "AHDXAPI Server is now started running `localtime`"; close F; $ret =qx(perl $xapipgm >>log/init/ahdxapi.init.log); }
************************************************************** ********************************************************** |
Vema Venkata
Aug 27 2003, 12:06 PM
thanx dude
-----Original Message-----
From: Bob Showalter [mailto:[Email Removed]]
Sent: Wednesday, 27 August 2003 6:28 PM
To: Vema Venkata; [Email Removed]
Subject: RE: help;help
Vema Venkata wrote:
QUOTE |
Folks, Here the following xapipgm.pl is executed well when iam executing manualy, but when iam trying to set it thru corntab iam not able to execute
The crontab settings are as follows
1-59 * * * * . /home/paradigm/.profile; /proj/ahd02/CAisd/site/mods/scripts/xapipgm.pl /proj/ahd02/CAisd/site/mods/scripts/log/init/ahdxapi.log
The error iam getting is as follows
***************************** sh: log/init/ahdxapi.init.log: cannot create
|
This appears to be coming from the qx() line at the end of the script below.
You seem to be making assumptions about the current directory which are not
valid. Either use chdir() in your script to set the working directory, or
use a full path to your log file.
QUOTE |
*****************************
************************************************************** ******************************** #!/proj/ahd02/CAisd/ActivePerl-5.6.0.618/bin/perl #/usr/local/bin/perl $xapipgm = "srvtst26.pl"; $ret = qx ( pgrep -f srvtst26); if ($? eq 0){ $ret = qx(pgrep - f $xapipgm); print "AHD XAPI SERver ($xapipgm) Running with Process ID : $$"; } else { open F, ">> log/init/ahdxapi.init.log";
|
You don't check for errors here. I suspect this open is failing.
QUOTE |
print F "AHDXAPI Server is now started running `localtime`"; close F; $ret =qx(perl $xapipgm >>log/init/ahdxapi.init.log); }
************************************************************** ********************************************************** |
Bob Showalter
Aug 27 2003, 12:14 PM
Paul Archer wrote:
QUOTE |
Is there any (quick and easy) way to get a reverse range, like (10..1), rather than a standard (1..10)? The catch is to *not* use 'reverse'. I'm teaching Sun's perl course this week (DTP-250), and we were talking about working on arrays. The book had an exercise that had the student reverse an array by using pop (or shift, I don't remember). That section is before we talk about 'reverse', and I thought you'd be able to do it like: @array[0 .. $#array] = @array[$#array .. 0] ...but of course, having the range count down doesn't work.
|
This works:
@arr = map pop(@arr), @arr;
but seems overly tricky, IMO. The far more straightforward:
@arr = reverse @arr;
would be preferred.
If you're teaching a class, I think you want to avoid using trickery just to
steer clear of a concept you haven't introduced yet. I would either go ahead
and introduce reverse(), if your purpose is to reverse an array. Or, I would
stay away from reversing arrays if your purpose is to illustrate the range
opeator.
James Edward Gray II
Aug 27 2003, 12:30 PM
On Wednesday, August 27, 2003, at 05:39 AM, Ramprasad A Padmanabhan
wrote:
QUOTE |
IMHO this list is not for solving puzzles or doing school homework , It is for people learning perl who are getting stuck due to pure perl problems
|
My, seldom humble, opinion does not agree with yours. My feeling is
that we are here to help people learn Perl. Generally, that means
we're answering beginner level questions, but I don't think there is
any harm in stretching our skills a little when we can.
Paul's question was pure Perl and he expressed exactly what he needed
well. The question is a little odd, as there's probably not too good a
reason not to use reverse() in normal code. What if there was though?
Say reverse() was known to be super slow and performance counted. Is
the question alright now? Probably, but the question hasn't changed at
all.
The answers to Paul's question also show exactly why it is fine, again
in my opinion. I don't know about you, but I learned something from
the responses and I'm no beginner. I think that's a sign that we're
doing the right things.
Finally, while I agree we should not be DOING homework, I think it
would be a great crime to say we should not be helping with homework.
I think this is one of the best, if not THE best, places to learn more
Perl on the Internet. To deny someone that resource because they are a
part of any demographic, especially students who hopefully want to
learn, is morally wrong, I think. Of course, this isn't too
significant as Paul's question was not homework.
While I'm quite certain I do not speak for everyone here, I just wanted
to make it clear, to Paul at least, that you do not speak for me either.
James
Jenda Krynicky
Aug 27 2003, 01:02 PM
From: Paul Archer <[Email Removed]>
QUOTE |
Is there any (quick and easy) way to get a reverse range, like (10..1), rather than a standard (1..10)? The catch is to *not* use 'reverse'. I'm teaching Sun's perl course this week (DTP-250), and we were talking about working on arrays. The book had an exercise that had the student reverse an array by using pop (or shift, I don't remember). That section is before we talk about 'reverse', and I thought you'd be able to do it like: @array[0 .. $#array] = @array[$#array .. 0] ...but of course, having the range count down doesn't work.
|
$array[-1] is the last item, $array[-scalar(@array)] is the first so:
@array[0 .. $#array] = @array[map -$_, (1 .. scalar(@array))];
Jenda
===== [Email Removed] ===
http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery
Jenda Krynicky
Aug 27 2003, 01:06 PM
From: "Jenda Krynicky" <[Email Removed]>
QUOTE |
From: Paul Archer <[Email Removed] Is there any (quick and easy) way to get a reverse range, like (10..1), rather than a standard (1..10)? The catch is to *not* use 'reverse'. I'm teaching Sun's perl course this week (DTP-250), and we were talking about working on arrays. The book had an exercise that had the student reverse an array by using pop (or shift, I don't remember). That section is before we talk about 'reverse', and I thought you'd be able to do it like: @array[0 .. $#array] = @array[$#array .. 0] ...but of course, having the range count down doesn't work.
$array[-1] is the last item, $array[-scalar(@array)] is the first so:
@array[0 .. $#array] = @array[map -$_, (1 .. scalar(@array))];
|
Actually
@array = @array[map -$_, (1 .. scalar(@array))];
is good enough.
Jenda
===== [Email Removed] ===
http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery
Randal L. Schwartz
Aug 27 2003, 02:33 PM
QUOTE |
"Jeff" == Jeff 'Japhy' Pinyan <[Email Removed]> writes:
|
Jeff> On Aug 26, Paul Archer said:
QUOTE |
Just a quick tip, which the docs mention that 'exists' and 'defined' will let you know if a particular element of a hash exists, or is defined, they work on arrays just as well.
|
Jeff> Yeah, but I really think the semantics of them on arrays is
Jeff> iffy. I don't use them on arrays... at least I try my best not
Jeff> to.
And they were added to support pseudo-hashes, which are now going away,
so don't count on them to work forever either.
print "Just another Perl hacker,"
--
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +
<[Email Removed]> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!
Titu Kim
Aug 27 2003, 02:35 PM
Thanks for the reply.
Thank you for pointing out Error module and try
and catch block. However, I am trying to avoid
installing extra module.
I found an interesting behavior in my script. In a
subroutine, I perform an insert (RaiseError=>0), then
i check $dbh->state(Always false if success). If
$dbh->state is false (Here I assume failure is caused
by key constraint), then I update the record. The
interesting part is, if the update statement is within
the caller subroutine, the record is updated. If i put
the update statement in another subroutine and have
the main subroutine to call it, update will not work
and no error is returned by update. Here is the code
snippet that will not work and work.
Working version
===============================================
my $sth=$dbh->prepare(qw {insert_query});
$sth->execute(@bind_param);
if($sth->state){
$sth=$dbh->prepare(qw {update_query});
$sth->execute(@bind_param);
}
$dbh->commit();
================================================
Bad version
================================================
my $sth=$dbh->prepare(qw {insert_query});
$sth->execute(@bind_param);
if($sth->state){
updateSubRoutine($dbh, $param1, $param2);
}
$dbh->commit();
*********updateSubRoutine**********
sub updateSubRoutine{
my ($dbh,$param1, $param2) = @_;
my $sth = $dbh->prepare(qw { update_query});
$sth->execute(@params);
#$dbh->commit(); also don't work.
}
***********************************
Can someone give me some suggestions?
Thanks.
--- "Hanson, Rob" <[Email Removed]> wrote:
QUOTE |
Take a look at the Error module (although you can use eval as well).
use DBI; use Error qw(:try);
my $dbh = DBI->connect(...); $dbh->{RaiseError} = 1;
try { $dbh->do("insert ..."); } catch Error with { print STDERR "Insert failed!"; }
$dbh->do("update ...");
...Or if you only want to update when the insert fails, then put the insert in the catch block.
Rob
-----Original Message----- From: Titu Kim [mailto:[Email Removed]] Sent: Wednesday, August 27, 2003 2:37 PM To: [Email Removed] Subject: How to cate DBI error and pass the control to subroutine?
Hi, I am using DBI and DBD to insert into database. If the insert fails because of the key constraints, I want to continue to update that record. How can I it do this after I issue $sth->execute() statement?
Thanks.
__________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com
-- To unsubscribe, e-mail: [Email Removed] For additional commands, e-mail: [Email Removed] |
__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com
Rob Hanson
Aug 27 2003, 06:07 PM
Take a look at the Error module (although you can use eval as well).
use DBI;
use Error qw(:try);
my $dbh = DBI->connect(...);
$dbh->{RaiseError} = 1;
try {
$dbh->do("insert ...");
}
catch Error with {
print STDERR "Insert failed!";
}
$dbh->do("update ...");
....Or if you only want to update when the insert fails, then put the insert
in the catch block.
Rob
-----Original Message-----
From: Titu Kim [mailto:[Email Removed]]
Sent: Wednesday, August 27, 2003 2:37 PM
To: [Email Removed]
Subject: How to cate DBI error and pass the control to subroutine?
Hi,
I am using DBI and DBD to insert into database. If
the insert fails because of the key constraints, I
want to continue to update that record. How can I it
do this after I issue $sth->execute() statement?
Thanks.
__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
Dan Muey
Aug 27 2003, 08:18 PM
QUOTE |
--Thanks for the reply:
--I think I'm well on my way, but, I'm looking --at the results and the 'Programming the PERL DBI' --book and it says that selectrow_array returns the --value of the first field.
|
It returns an array:
my ($one,$two,$three) = $dbh->selectrow_array("SELECT one,two,three FROM table WHERE ID=1");
Or
my @stuff = $dbh->selectrow_array("SELECT one,two,three FROM table WHERE ID=1");
It return an array for the first *row* so if it's a multirow select then you'll only get the first *row* returned.
Why not simply try some of the stuff and experiment and see what happens when you do different things.
QUOTE |
--selectall_arrayref and selectcol_arrayref --doesn't seem to help.
--how can I return all of the fields that --was selected?
|
All fields into an array : selectrow_array()
All Rows you have to do the prepare execute while finish dance
I actually have a simpler way to do it I'm going to have in
module if I ever hear back from the PAUSE folks. But until then that's it.
HTH
Dmuey
QUOTE |
--Thanks again!
-X
[snip]
I have a script where I want to
* connect to database * create a subroutine where it executes and returns the value of the SQL * pass that value to another area to check and IF statement * continue with program
I am having problems trying to figure out if the SQL is actually being processed and if so, why the value isn't being returned.
do() returns 0E0 on error and number of rows affected as provided by mysql. I think you want selectrow_array()
my($joe,$mama) = $dbh->selectrow_array('SELECT joe,mama FROM joemama WHERE ID=83');
HTH
DMuey
[snip script]
|
Scott Taylor
Aug 27 2003, 08:22 PM
At 09:30 AM 08/27/2003, Johnson, Shaunn wrote:
QUOTE |
--Thanks for the reply:
--I think I'm well on my way, but, I'm looking --at the results and the 'Programming the PERL DBI' --book and it says that selectrow_array returns the --value of the first field.
--selectall_arrayref and selectcol_arrayref --doesn't seem to help.
--how can I return all of the fields that --was selected?
|
Sorry, I missed the first bit of this thread...
Is this what you are looking for?
my $SQL = qq[
select ID, CusName, OtherField
from myTable
];
my $sth = $dbh->prepare($SQL)||print "$SQL";
$sth->execute||exit print "Could not execute:n
$SQLn";
while ( my ( $id, $cusname, $otherfield ) )
= $sth->fetchrow ) {
do some things here with new variables
}
....
that's my favorite way, or you can replace list of variable names with an
array like @columns and then refer to them by $columns[0] $columns[1] etc...
Shaunn Johnson
Aug 27 2003, 08:47 PM
--Howdy:
--Sorry, I should have added more detail in
--my reply. When I did the posted suggestion,
--I only got one column, but if I ran the SQL
--by hand, I got them all.
--But in the example below, you list out the
--variables and then get the entire row.
--I thought I could just pull in the
--results of the query with one variable
--($sql).
QUOTE |
--I think I'm well on my way, but, I'm looking --at the results and the 'Programming the PERL DBI' --book and it says that selectrow_array returns the --value of the first field.
It returns an array: my ($one,$two,$three) = $dbh->selectrow_array("SELECT one,two,three FROM table WHERE ID=1"); Or my @stuff = $dbh->selectrow_array("SELECT one,two,three FROM table WHERE ID=1");
It return an array for the first *row* so if it's a multirow select then you'll only get the first *row* returned.
Why not simply try some of the stuff and experiment and see what happens when you do different things.
--selectall_arrayref and selectcol_arrayref --doesn't seem to help.
--how can I return all of the fields that --was selected?
All fields into an array : selectrow_array()
|
--i was wondering why my other script that used
--the prepare / execute / while ($whatever) { ...}
--did what i wanted (but overkill for one silly row).
--i thought the docs said that selectrow_array()
--puts all of the 'prepare' / 'execute' in one
--function and made the need for the extra 15
--lines of code go away.
--you're right: i have to continue playing with
--it until i get the right runes.
QUOTE |
All Rows you have to do the prepare execute while finish dance I actually have a simpler way to do it I'm going to have in module if I ever hear back from the PAUSE folks. But until then that's it.
|
--thanks again!
[snip]
-X
Dan Muey
Aug 27 2003, 08:56 PM
QUOTE |
--Howdy:
--Sorry, I should have added more detail in --my reply. When I did the posted suggestion, --I only got one column, but if I ran the SQL --by hand, I got them all.
--But in the example below, you list out the --variables and then get the entire row. --I thought I could just pull in the --results of the query with one variable --($sql).
|
Nope. It returns an array so ($variable) is the first element of the array
($variable,$variable2) is the first two elements in the array etc...
If for some bizarre reason you need to sleect several fields and then get them together in a string (IE one variable)
my $result = join('', $dbh->selectrow_array("..."));
But that seems pointless.
Try this:
my @list = $dbh->selectrow_array(....);
for(@list) { print "-$_-n"; }
@list will have every field requested by your query
($var,$var) is an array also it just assigns the elements of the array to the variables listed and if there is two vars listed you get the first two elements of the array assigned to them.
At the risk of sounding sarcastic : selectrow_array will 'select' a 'row' into an 'array' :)
Does that make more sense now?
DMuey
QUOTE |
--I think I'm well on my way, but, I'm looking --at the results and the 'Programming the PERL DBI' --book and it says that selectrow_array returns the --value of the first field.
It returns an array: my ($one,$two,$three) = $dbh->selectrow_array("SELECT one,two,three FROM table WHERE ID=1"); Or my @stuff = $dbh->selectrow_array("SELECT one,two,three FROM table WHERE ID=1");
It return an array for the first *row* so if it's a multirow select then you'll only get the first *row* returned.
Why not simply try some of the stuff and experiment and see what happens when you do different things.
--selectall_arrayref and selectcol_arrayref --doesn't seem to help.
--how can I return all of the fields that --was selected?
All fields into an array : selectrow_array()
--i was wondering why my other script that used --the prepare / execute / while ($whatever) { ...} --did what i wanted (but overkill for one silly row). --i thought the docs said that selectrow_array() --puts all of the 'prepare' / 'execute' in one --function and made the need for the extra 15 --lines of code go away.
--you're right: i have to continue playing with --it until i get the right runes.
All Rows you have to do the prepare execute while finish dance I actually have a simpler way to do it I'm going to have in module if I ever hear back from the PAUSE folks. But until then that's it.
--thanks again!
[snip]
-X
|
Eric Walker
Aug 27 2003, 09:15 PM
I don'tknow if this is the best way but I ended up doing this:
my $UID = getpwuid($<);
my @GROUPS = split(" ",`groups $UID`);
Which gets the groups that the user who is running my script belongs
too.
correct me if I am wrong?
EDOG
On Wed, 2003-08-27 at 16:00, Dan Muey wrote:
Howdy
QUOTE |
I want to us the variable $< to get the REAL UID of the perl program that is running. How can I get the users name from that number it gives me?
|
Depends on the system.
Have you looked on cpan for a module that does that?
You can always qx() the same way you'd do it via command line.
IE if you can do
$ /usr/bin/sername 0
root
$
Then you can do perhaps:
my $userfromid = qx(/usr/bin/username $<);
HTH
DMuey
--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
David
Aug 27 2003, 09:46 PM
Eric Walker wrote:
QUOTE |
Hello all I want to us the variable $< to get the REAL UID of the perl program that is running. How can I get the users name from that number it gives me?
|
the getpwuid function in scalar context gives you the user of the uid:
[panda]$ perl -le 'print scalar getpwuid($<)'
david
[panda]$
perldoc -f getpwuid
david
Bryan Harris
Aug 28 2003, 05:02 AM
QUOTE |
The fork concept can be quite confusing at first, but it is actually quite simple, once you get used to it. Check out the output of this little program:
|
[ very interesting stuff cut out ]
Wild! Why would anyone ever use this? Why would you ever want to clone
yourself at the current point and have both continue on running? I guess I
could see it being a smooth way to process a hundred files all at once
(sort-of)... I don't get it.
[ more interesting stuff cut out ]
QUOTE |
with '&' your program won't wait for the other-program to finish, but the other-program process will die when your program (the parent process) finishes.
|
Why is this? Does that mean if I create a new tcsh shell, run an app, kill
the tcsh shell before the app finishes, that the app will die too? Why have
parent/child relationships in processes? Are there such things as
grandchildren/grandparents?
QUOTE |
Of course you want your program to finish without killing the child processes in the process (pun definitely intended) and for that you need your child processes to create new sessions with setsid().
|
What is a session? I've never heard of that...
QUOTE |
You can take a look at Proc::Daemon module on CPAN, but it's not exactly what you need, mostly because it redirects STDOUT to /dev/null, while you want your processes to write to STDOUT (by the way, are you sure about that? it can result in a total mess printed on your terminal) but still you may want to read its source to see how it works: http://search.cpan.org/src/EHOOD/Proc-Daemon-0.03/Daemon.pm
|
Yes, I absolutely want all output going to STDOUT. Thanks for foreseeing a
potential problem, though...
QUOTE |
use POSIX 'setsid'; sub forkrun ($) { my $cmd = pop; defined(my $pid = fork) or die "$0: fork: $!n"; unless ($pid) { setsid or die "$0: setsid: $!n"; exec $cmd; } return $pid; }
|
Yes! This works terrifically!
How does the fork part work within subroutines? I'm guessing the part
starting with "unless" looks to see if it's now a child process, and if so,
to quit the current perl script and start off $cmd. Is that right?
It works, so that part's taken care of. Now I just have to figure out how
it works. =) Thanks a lot zsdc.
- Bryan
Ramprasad A Padmanabhan
Aug 28 2003, 05:06 AM
Sharad Gupta wrote:
QUOTE |
Hi all,
Any ideas on how do i send an interrupt signal to the connection made via Net::Telnet.
Thanx, -Sharad |
Which OS?
On Unix like systems, You can find the PID of the script and send the
signal on the shell
like
kill -15 $PID
Ram
Tassilo Von Parseval
Aug 28 2003, 06:06 AM
On Wed, Aug 27, 2003 at 06:00:40PM -0700 Reid Beels wrote:
QUOTE |
I'm trying to install a module (Image::Imlib2) which depends on DynaLoader being able to find an external C library. Normally, this wouldn't cause a problem but I'm being forced to install the module on a system which I do not have root access on and thus must store the both the module and the library it seeks in a nonstandard location. The location for the module is working fine, as expected, but I have yet to find a way to tell DynaLoader to look in the correct place for the library. I have tried adding
push(@DynaLoader::dl_library_path, '/home/lwire/perllib/clib');
to both the script which I am calling Image::Imlib2 from and to Imlib2.pm itself. Either way, I receive the following error:
Can't load '/home/lwire/perllib/lib/perl5/5.6.1//i686-linux/auto/Image/Imlib2/ Imlib2.so' for module Image::Imlib2: libImlib2.so.1: cannot open shared object file: No such file or directory a t /usr/lib/perl5/5.6.1/i686-linux/DynaLoader.pm line 206.
Do I need to be defining dl_library_path somewhere else or is there some other method that I can use to define the search path??
|
Rather LD_LIBRARY_PATH. Set this environment variable so that it
contains the directory where the imlib2 object files reside. I think
that DynaLoader uses dlopen(3) and related functions to dynamically
include a library and those functions look in LD_LIBRARY_PATH.
Tassilo
--
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.t$&."'!#+sexisexiixesixeseg;y~n~~dddd;eval
GMC
Aug 28 2003, 09:00 AM
[Email Removed] (Steve Grazzini) wrote in <20030711203729.GA24200
@grazzini.net>:
QUOTE |
On Fri, Jul 11, 2003 at 03:32:10PM -0500, [Email Removed] wrote: On Fri, 11 Jul 2003 15:56:31 -0400, "Paul Kraus" <[Email Removed]> wrote: are there any good free news servers out there that have access to this list?
Sorry I can't help on the news front, I don't have access either so if there is a free alternative I might look into it.
All the perl.org mailing lists are mirrored at nntp.perl.org.
|
Just point any News Reader program to nntp.perl.org. No password is required
and you can read and post from anywhere!!
-Good Luck
GMC
Zsdc
Aug 28 2003, 01:55 PM
Bryan Harris wrote:
QUOTE |
The fork concept can be quite confusing at first, but it is actually quite simple, once you get used to it. Check out the output of this little program:
[ very interesting stuff cut out ]
Wild! Why would anyone ever use this? Why would you ever want to clone yourself at the current point and have both continue on running? I guess I could see it being a smooth way to process a hundred files all at once (sort-of)... I don't get it.
|
Servers often work this way. There's a process listening on a port but
when someone connects, it doesn't serve the actual request (which would
block the server and no one else could connect until it's done) but only
forks the child, which then serves the request, and the parent keeps
listening for another requests and forks another children at the same time.
As for the client side, you could for example have a mail client
downloading mail in the background, while the user can keep writing and
sending mail at the same time, etc. Check out this example:
#!/usr/bin/perl -w
open F, '+>', "$0-result" or die $!;
defined(my $pid = fork) or die $!;
unless ($pid) {
# child:
sleep 5; # an important time consuming task...
print F "123n";
exit;
}
# parent:
print "Not yet... Do something else.n" and sleep 1 until -s F;
seek F, 0, 0;
print "Done! The result is ", <F>;
It could be written better with pipes, or real temp files, but it's
cleaner that way. The child could do something more interesting than
sleeping, like downloading a webpage from a slow server, without totally
freezing our program. The parent might decide to wait only ten seconds
and then give up, or try again downloading from another mirror, etc.
Instead of one process, you can have few processes running
simultaneously and interacting with each other, while every one of them
is a different incarnation of the same program. It can be very powerful.
QUOTE |
[ more interesting stuff cut out ]
with '&' your program won't wait for the other-program to finish, but the other-program process will die when your program (the parent process) finishes.
Why is this? Does that mean if I create a new tcsh shell, run an app, kill the tcsh shell before the app finishes, that the app will die too? Why have parent/child relationships in processes? Are there such things as grandchildren/grandparents?
|
Yes. Actually, there's a whole genealogy tree. The process with ID 1
(usually called init) is the protoplast of every other process running
on the system. This is the only process without a parent.
The killing of children makes sense when e.g. I open an xterm window and
run "man fork". What I have now is a shell process which is a child of
xterm, a man process which is a child of the shell and a pager (for
scrolling man's output) which is a child of man. Now, when I just close
the xterm window, the pager, man and shell are killed as well. It makes
sense, because keeping them running (sleeping, actually) would be pointless.
But sometimes you don't want that. For example, your ssh connection
could die, everything is killed and you have to connect and login once
again and start everything from the beginning. If you don't want that,
then check out this great little program:
http://www.gnu.org/software/screen/It's truely amazing.
QUOTE |
Of course you want your program to finish without killing the child processes in the process (pun definitely intended) and for that you need your child processes to create new sessions with setsid().
What is a session? I've never heard of that...
|
A session is basically (it's an oversimplification) a bunch of processes
which get killed if you close the session, because they are important
only for that session (like the example with xterm). For more
informations see:
man setsid
http://linux.ctyme.com/man/man2993.htm man getsid
http://linux.ctyme.com/man/man0960.htm man setpgid
http://linux.ctyme.com/man/man2984.htmQUOTE |
You can take a look at Proc::Daemon module on CPAN, but it's not exactly what you need, mostly because it redirects STDOUT to /dev/null, while you want your processes to write to STDOUT (by the way, are you sure about that? it can result in a total mess printed on your terminal) but still you may want to read its source to see how it works: http://search.cpan.org/src/EHOOD/Proc-Daemon-0.03/Daemon.pm
Yes, I absolutely want all output going to STDOUT. Thanks for foreseeing a potential problem, though...
|
Instead of /dev/null you could also redirect STDOUT to real files (or
pipes or sockets or whatever), so you could capture and access it
without all the mess on your screen.
QUOTE |
use POSIX 'setsid'; sub forkrun ($) { my $cmd = pop; defined(my $pid = fork) or die "$0: fork: $!n"; unless ($pid) { setsid or die "$0: setsid: $!n"; exec $cmd; } return $pid; }
Yes! This works terrifically!
|
Great.
QUOTE |
How does the fork part work within subroutines? I'm guessing the part starting with "unless" looks to see if it's now a child process, and if so, to quit the current perl script and start off $cmd. Is that right?
|
Yes. The child goes inside the unless block (it has 0 in $pid, because
it was returned by the fork call) while the parent skips the unless
block (it has child's PID in $pid which is not 0) and goes directly to
the return.
Actually, there should be a die or exit call after the exec, just in
case the command could not be run, because otherwise the child would
also return from the subroutine and run the rest of the program as well,
just like the parent. So instead of:
exec $cmd;
there should be:
exec $cmd or die "exec $cmd: $!n";
As for quitting, actually exec doesn't even quit the Perl script in a
way exit() or die() does (no object destructors and not even END blocks
will be called in your process after a successful exec). The system
replaces our process image with a new one, without giving our process
any chance to do anything more. Try this:
#!/usr/bin/perl -l
BEGIN { print "BEGIN block" }
END { print "END block" }
print "Program body";
die "I'm dying here";
print "I'm already dead";
print "This is never printed";
The BEGIN block is always run before the main program starts, and the
END block after it ends, no matter if it's just the end of a file, or
exit() was called, or even die(). But here:
#!/usr/bin/perl -l
BEGIN { print "BEGIN block" }
END { print "END block" }
print "Program body";
exec "echo This is echo";
print "I'm already dead";
print "This is never printed";
nothing will be called after exec. If you add -w switch or "use
warnings;" perl will give you a warning:
Statement unlikely to be reached at ./exec-test-2 line 6.
(Maybe you meant system() when you said exec()?)
This is why it's always a good idea to have warnings turned on. For more
about exec, see:
perldoc -f exec
http://www.perldoc.com/perl5.8.0/pod/func/exec.html man exec
http://linux.ctyme.com/man/man0683.htm man execve
http://linux.ctyme.com/man/man0686.htmQUOTE |
It works, so that part's taken care of. Now I just have to figure out how it works. =) Thanks a lot zsdc.
|
I'm glad I could be helpful. This subject usually causes lots of
confusion. I hope others could also find it interesting and didn't mind
if I was a little bit off topic.
--
ZSDC Perl and Systems Security Consulting
On Thu, 28 Aug 2003, Ramprasad A Padmanabhan wrote:
QUOTE |
Sharad Gupta wrote: Hi all,
Any ideas on how do i send an interrupt signal to the connection made via Net::Telnet.
Thanx, -Sharad
Which OS? On Unix like systems, You can find the PID of the script and send the signal on the shell
like kill -15 $PID
Ram
|
you could also do:
killall -KILL name_of_application
HTH..
Denis
Chuck Fox
Aug 28 2003, 06:19 PM
What about using perl to massage the data into a file (or hash) and then
using gnuplot ( or Graph::Plot )
Chuck
[Email Removed] wrote:
QUOTE |
--On Wednesday, August 27, 2003 1:29 PM -0500 "Akens, Anthony" <[Email Removed]> wrote:
Just wanted to look into a "for fun" project, after a recent project that wasn't much fun at all... Our organization got hit by the blaster worm, which hit many, many windows boxes. The *nix boxes (which I manage) were of course unaffected, except by the total lack of bandwidth available to them. Except for one. We have the syslog on our PIX firewall forward on to one of my boxes, so I have an interested detailed log of how the blaster worm spread on our network.
So much for the history, now on to some ideas... I thought it would be interesting to plot two things - 1) How many hits per minute, and 2) Total compromised systems over time.
I thought of perl immediately as a good tool to break this rather large file down, but being a newbie I'm not sure how to begin.
As much as I like Perl, my first thought for something like this would not be Perl, but some sort of statistical package that has routines already built-in to handle descriptive statistics. I'd use SAS, since I have it available at work and I'm familiar with it, but SPSS, Minitab, and other packages would work well, too. You might also try R <URL:http://www.r-project.org/>, which is an open-source (GNU Public License) language for statistical programming and graphics. It's modelled on the S language (a commercial product). (I still might use Perl just to extract the parts I wanted to analyze and put them in a format the stat package could read easily.)
But if you're doing it just for practice, I won't argue. :-)
|
Zsdc
Aug 28 2003, 06:50 PM
Silja Rajendran wrote:
QUOTE |
I am a unix admin tasked with writing script for synchronizing the password between two servers. I though it can be done better using perl and hence this question.
|
Dan Muey
Aug 28 2003, 08:16 PM
Howdy
QUOTE |
This should be very straightforward:
print "Enter 5 of your favorite foods: "; $favorites = ( <STDIN> );
|
[snip]
QUOTE |
The desired output would be:
food1 food2 food3 food4 food5
food1 food2 food3 food4 food5
Can someone steer me in the right direction?
|
my @favs = split(/s+/, $fav);
print @favs;
for(@favs) { print "-$_-n"; }
HTH
Dmuey
K Old
Aug 29 2003, 02:48 AM
On Wed, 2003-08-27 at 14:29, Akens, Anthony wrote:
QUOTE |
Hello all,
Just wanted to look into a "for fun" project, after a recent project that wasn't much fun at all... Our organization got hit by the blaster worm, which hit many, many windows boxes. The *nix boxes (which I manage) were of course unaffected, except by the total lack of bandwidth available to them. Except for one. We have the syslog on our PIX firewall forward on to one of my boxes, so I have an interested detailed log of how the blaster worm spread on our network.
So much for the history, now on to some ideas... I thought it would be interesting to plot two things - 1) How many hits per minute, and 2) Total compromised systems over time.
I thought of perl immediately as a good tool to break this rather large file down, but being a newbie I'm not sure how to begin. The format of each line is as follows (IPs changed to protect the lazy):
Aug 20 16:57:28 pix %PIX-3-106011: Deny inbound (No xlate) icmp src inside:10.0.0.10 dst inside:10.1.1.23 (type 8, code 0)
For the first bit I know I would need to just create a counter for each minute, probably using a regex to increment the counter?
For the second I would need to count the source machine IPs, and use a hash(?) to keep track of them, and when each first appears in the logs, then plot that over time?
|
Tony,
Well, my recommendation is the GD::Graph module(look for it on CPAN).
It's a pretty good module once you get everything working behind the
scenes(check the pod docs for info on setting it up).
If you're graphing over time, you'll need to collect the data and store
it in another source (files, database, etc).
Use GD::Graph to put the calculated data into arrays/hashes and it will
build graphs and charts out of it. It handles all all different types
of charts and graphs(line, pie, bar, etc)
Hope this helps,
Kevin
QUOTE |
Can anyone give me some ideas where to start? This worm spread incredibly fast in our network, should be interesting to see it charted.
Tony -- |
K Old <[Email Removed]>
Alan C.
Aug 29 2003, 06:00 AM
Joshua Lokken wrote:
[ . . ]
QUOTE |
While your way is much easier and works well, I wonder why my original syntax did not produce the desired result?
|
Your (next, below) original syntax does produce the desired result here
(tested). Win32 Activestate Perl 5.61 build 633
#!perl
print "Enter 5 of your favorite foods: ";
$favorites = ( <STDIN> );
# @foodlist=split(' ', $favorites);
@foodlist=split / /, $favorites;
print "@foodlistn";
print "$foodlist[0]n";
print "$foodlist[1]n";
Tested, Either of those two split lines produces the same result for me.
I don't know reason(s) to prefer one over the other.
(in addition to warn and strict), default behavior(s) utilized next
(tested, works)
#!perl
use warnings;
use strict;
print "Enter 5 of your favorite foods: ";
$_ = ( <STDIN> );
my @foodlist = split;
print @foodlist, "nn";
print "$foodlist[0]n";
print "$foodlist[1]n";
# hmm, @foodlist prints without space between each word; I not sure how
to get a space put back in between each word there.
--
Alan.
Editor says: "remove dot twice if reply"
Bob Showalter
Aug 29 2003, 11:15 AM
Johnson, Shaunn wrote:
QUOTE |
Howdy:
With the PostgreSQL DBI, you can get a number of tuples (with ntuples) from some previously SQL query.
For example, I have :
[snip] use Pg;
|
Shaunn, that's not DBI.
QUOTE |
... My question: Is there an Oracle version of 'ntuples'? I don't see any reference of this in the Perl DBI book.
|
With DBI, statement handles have a "rows" method you can use to determine
the number of rows that have been fetched. Be sure to read the docs to see
the caveats on the use of this method.
Nyimi Jose
Aug 29 2003, 02:52 PM
Found interesting info from here :
http://www.manning.com/getpage.html?projec...ame=source.htmlOthers are welcome :-)
Jos.
-----Original Message-----
From: NYIMI Jose (BMB)
Sent: Friday, August 29, 2003 10:44 AM
To: K Old; Akens, Anthony
Cc: [Email Removed]
Subject: RE: Graphing/Plotting over time
Cool !
I was just dealing with following needs:
* parse a text files on daily basis
* put the result into database
* buit a web application upon above database
* provide the client a web form where he can choose which graph to see
* on submit, connect to database, plot the graph and render it to the client as an image
For the time beeing, i'm busy writing the parser using Parse::RecDescent module. The text file is a little bit complex, so we choose to parse it via buiding grammar. The second part will be, how to render the graph to the web client.
Is GD::Graph module sufficient to handle above requirements ?
Any ideas/advices is welcome.
Thanks in advance.
Jos.
-----Original Message-----
From: K Old [mailto:[Email Removed]]
Sent: Friday, August 29, 2003 5:49 AM
To: Akens, Anthony
Cc: [Email Removed]
Subject: Re: Graphing/Plotting over time
On Wed, 2003-08-27 at 14:29, Akens, Anthony wrote:
QUOTE |
Hello all,
Just wanted to look into a "for fun" project, after a recent project that wasn't much fun at all... Our organization got hit by the blaster worm, which hit many, many windows boxes. The *nix boxes (which I manage) were of course unaffected, except by the total lack of bandwidth available to them. Except for one. We have the syslog on our PIX fire For the second I would need to count the source machine IPs, and use a hash(?) to keep track of them, and when each first appears in the logs, then plot that over time?
|
Tony,
Well, my recommendation is the GD::Graph module(look for it on CPAN).
It's a pretty good module once you get everything working behind the scenes(check the pod docs for info on setting it up).
If you're graphing over time, you'll need to collect the data and store it in another source (files, database, etc).
Use GD::Graph to put the calculated data into arrays/hashes and it will build graphs and charts out of it. It handles all all different types of charts and graphs(line, pie, bar, etc)
Hope this helps,
Kevin
QUOTE |
Can anyone give me some ideas where to start? This worm spread incredibly fast in our network, should be interesting to see it charted.
Tony -- |
K Old <[Email Removed]>
--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
**** DISCLAIMER ****
"This e-mail and any attachment thereto may contain information which is confidential and/or protected by intellectual property rights and are intended for the sole use of the recipient(s) named above.
Any use of the information contained herein (including, but not limited to, total or partial reproduction, communication or distribution in any form) by other persons than the designated recipient(s) is prohibited.
If you have received this e-mail in error, please notify the sender either by telephone or by e-mail and delete the material from any computer".
Thank you for your cooperation.
For further information about Proximus mobile phone services please see our website at
http://www.proximus.be or refer to any Proximus agent.
--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
Paul Kraus
Aug 29 2003, 04:58 PM
Typeo should be $my not #my
-----Original Message-----
From: Paul Kraus [mailto:[Email Removed]]
Sent: Friday, August 29, 2003 1:55 PM
To: 'Nigel Peck - MIS Web Design'; [Email Removed]
Subject: RE: or operator
If ($my eq $this) || (#my eq $this2) {
code;
}else{
more code;
}
HTH
-----Original Message-----
From: Nigel Peck - MIS Web Design [mailto:[Email Removed]]
Sent: Friday, August 29, 2003 1:50 PM
To: [Email Removed]; [Email Removed]
Subject: or operator
In Perl can I say:
if this = that or that or that
instead of saying:
if this = that or this = that or this = that
Cheers,
Nigel
Managing Director
MIS Web Design
http://www.miswebdesign.com/Administrator
AccessifyForum.com
http://www.accessifyforum.com/ --
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
Kevin Pfeiffer
Aug 29 2003, 07:17 PM
Hi,
In article
<[Email Removed]>, Rob
Hanson wrote:
QUOTE |
Just to throw out another idea, you can also do this...
my $name = "Anthony Bob"; my @letters = grep {!/s/} split('', $name);
# to test print "@letters";
It also looks like you wanted upper case. You can do that with this...
my $name = "Anthony Bob"; my @letters = grep {!/s/} split('', uc($name));
In both cases the split cuts it up into a list of characters, and grep filters out the spaces (also newlines & tabs).
|
No need to filter twice I think (also from perldoc -f split):
print "$_n" foreach (split / */, uc $name);
Only 505 unread messages to go... :-
-K
--
Kevin Pfeiffer
International University Bremen
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
Rob Hanson
Aug 29 2003, 08:37 PM
QUOTE |
What is the best library to handle pictures?
|
Image::Magick is a great tool for creating thumbnails, it is both easy and
the shrunk images still look good.
http://search.cpan.org/author/JCRISTY/Perl...-5.57/Magick.pmIf you are running the ActiveState version of Perl, be sure to get it from
there instead of CPAN. You can install this with ActiveState Perl by
running "ppm install Image-Magick" at the command line.
For HTML creation you might find it easier to use templates, and have your
Perl program just fill in the blanks. The are some complex kits out there,
so you might want to try HTML::Template first, it is very easy to use.
http://search.cpan.org/author/SAMTREGAR/HT...2.6/Template.pmQUOTE |
What resources from Perl do you suggest I to use?
|
It depends. If you are comfortable with manpages, then check out the
documentation that comes with Perl. If not, pick up a copy of Learning Perl
published by O'Reilly & Assoc.
http://www.oreilly.com/catalog/lperl3/....Or Learning Perl on Win32 if you are running it on Windows.
http://www.oreilly.com/catalog/lperlwin/Once you start getting into Perl and need to explore more complex topics,
check out their other specialized Perl books... they have lots.
http://perl.oreilly.com/Rob
-----Original Message-----
From: Geraldo Milagre [mailto:[Email Removed]]
Sent: Friday, August 29, 2003 5:19 PM
To: [Email Removed]
Subject: Managing Pictures with Perl
Hi,
I would like to write a program to manage my pictures colection and
generate statics html pages for view the pics. I would like to use Perl
to do this, as a way to learning more about the language. What resources
from Perl do you suggest I to use? What is the best library to handle
pictures?
Thanks a lot.
--
Geraldo Milagre
[Email Removed]
(19)9121-0704
(19)3236-1305
--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
John W. Krahn
Aug 30 2003, 05:25 PM
Mike wrote:
QUOTE |
Well this is the final code I put together with everyones help from this group:
#!/usr/bin/perl use warnings; use strict;
print "Enter the path of the INFILE to be processed:n"; chomp (my $infile = <STDIN>); open(INFILE, $infile) or die "Can't open INFILE for input: $!"; print "Enter in the path of the OUTFILE:n"; chomp (my $outfile = <STDIN>); open(OUTFILE, ">$outfile") or die "Can't open OUTFILE for input: $!"; print "Enter in the LENGTH you want the sequence to be:n"; chomp (my $len = <STDIN>);
my ($name, @seq); while ( <INFILE> ) { chomp; unless ( /^s*$/ or s/^s*>(.+)// ) { $name = $1; my @char = ( split( // ), ( '-' ) x ( $len - length ) ); push @seq, ' '."@char $name"; } }
{ local $" ="n"; print OUTFILE "R 1 $lennnnn@seq"; # The top of the file is supposed
}
close INFILE; close OUTFILE;
[snip]
However, I forgot that sometime the imput data is like this:
dog agatgtagt agtggttga agggagc cat gcatcgatg agcatatgc mouse actagcatc acgtacgat
That is the sequence of letters can span multiple lines. I would like the above script to handle input data that can possibly span several lines as well as those that do not. and output as mentioned above.
|
You keep changing the specs Mike. :-) Based on your code and data above, this will work:
#!/usr/bin/perl
use warnings;
use strict;
print "Enter the path of the INFILE to be processed: ";
chomp( my $infile = <STDIN> );
open INFILE, $infile or die "Can't open $infile for input: $!";
print "Enter in the path of the OUTFILE: ";
chomp( my $outfile = <STDIN> );
open OUTFILE, ">$outfile" or die "Can't open $outfile for output: $!";
print "Enter in the LENGTH you want the sequence to be: ";
my ( $len ) = <STDIN> =~ /(d+)/ or die "Invalid length parameter";
print OUTFILE "R 1 $lennn"; # The top of the file is supposed
$/ = '>'; # Set input record separator
while ( <INFILE> ) {
chomp;
next unless s/^s*(S+)//;
my $name = $1;
my @char = ( /[acgt]/g, ( '-' ) x $len )[ 0 .. $len - 1 ];
print OUTFILE " @char $namen";
}
close INFILE;
close OUTFILE;
__END__
John
--
use Perl;
program
fulfillment
Jenda Krynicky
Aug 31 2003, 01:56 PM
From: "Nestor, John" <[Email Removed]>
QUOTE |
Sent this MacPerl yesterday, no response yet. But from what little I've seen on this error via google, I think it's a reg exp problem, not platform specific. Any ideas? Any documentation I should check out? All help accepted gratefully.
|
Please try and trim the erroring code a little. It's too long, and
since it has been qutoed and reformated it's next to impossible to do
anything with it.
You should also consider using some other characters than / for your
regexes. Something that would stand out more.
I think you'd agree that
$_ =~
s#(}{\b\fs24\cgrid0d+).(d+}{\fs24\cgrid0\{.*?\})#$1_$2NO
T_FOUND#;
reads much better than
$_=~s/(}{\b\fs24\cgrid0d+).(d+}{\fs24\cgrid0\{.*?\})/$1_
$2NOT_FOUND/;
Anyway ... it does seem to me that the problem really is in one of
the regexps. Try them out in a separate script.
Jenda
Jenda
===== [Email Removed] ===
http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery
Mike Robeson
Aug 31 2003, 02:15 PM
Yeah, the parameters keep changing because my buddy and I had
incorrectly remembered the format it was supposd to be (several times).
Sorry about that. Anyway, what you provided did work with some changes.
the code you sent didn't do anything other than give me the command
promt again - but I managed to get it to work anyway. However, I can't
seem to figure out why I cannot use this line:
my @char = ( split( // ), ( '-' ) x ( $len - length ) );
instead of this line:
my @char = ( /[a-z]/ig, ( '-' ) x $len )[ 0 .. $len - 1 ];
in the script - I get errors ( I mean there are other changes that need
to be made but these lines are my major focus). I just like the way the
first line of code calculates the amount of dashes to add. It's just an
aesthetic thing. :-) Note I changed it to a-z because we use many other
characters than "atcg", for example "n" means "unkown base". Also, just
do not understand as clearly the second line of code above as I do the
first. From what I can gather you are making, say, 50 dashes and then
"filling in" the dashes that match the charatcers within [a-z] from left
to right as long as there are characters to "fill in" the dashes. Does
that make sense?
Anyway, when I add "$/ = '>';" to the original script below I get a
contatination error (why?). Basically, I am trying to understand why
certain bits of code "break" the script and others don't. I find I learn
things better by trying alternate forms of code to figure out
relationships. However, I have been looking through my perl books like
crazy and can't seem to understand some of these relationships. I know
it will take time and experience... I guess I'll pick up another perl
book that provides another perspective.
Sorry about taking so long with this, I am trying to make an honest
effort to learn. :-)
-Thanks
-Mike
In article <[Email Removed]>, [Email Removed] (John W. Krahn)
wrote:
QUOTE |
Mike wrote:
Well this is the final code I put together with everyones help from this group:
#!/usr/bin/perl use warnings; use strict;
print "Enter the path of the INFILE to be processed:n"; chomp (my $infile = <STDIN>); open(INFILE, $infile) or die "Can't open INFILE for input: $!"; print "Enter in the path of the OUTFILE:n"; chomp (my $outfile = <STDIN>); open(OUTFILE, ">$outfile") or die "Can't open OUTFILE for input: $!"; print "Enter in the LENGTH you want the sequence to be:n"; chomp (my $len = <STDIN>);
my ($name, @seq); while ( <INFILE> ) { chomp; unless ( /^s*$/ or s/^s*>(.+)// ) { $name = $1; my @char = ( split( // ), ( '-' ) x ( $len - length ) ); push @seq, ' '."@char $name"; } }
{ local $" ="n"; print OUTFILE "R 1 $lennnnn@seq"; # The top of the file is supposed
}
close INFILE; close OUTFILE;
[snip]
However, I forgot that sometime the imput data is like this:
dog agatgtagt agtggttga agggagc cat gcatcgatg agcatatgc mouse actagcatc acgtacgat
That is the sequence of letters can span multiple lines. I would like the above script to handle input data that can possibly span several lines as well as those that do not. and output as mentioned above.
You keep changing the specs Mike. :-) Based on your code and data above, this will work:
#!/usr/bin/perl use warnings; use strict;
print "Enter the path of the INFILE to be processed: "; chomp( my $infile = <STDIN> ); open INFILE, $infile or die "Can't open $infile for input: $!";
print "Enter in the path of the OUTFILE: "; chomp( my $outfile = <STDIN> ); open OUTFILE, ">$outfile" or die "Can't open $outfile for output: $!";
print "Enter in the LENGTH you want the sequence to be: "; my ( $len ) = <STDIN> =~ /(d+)/ or die "Invalid length parameter";
print OUTFILE "R 1 $lennn"; # The top of the file is supposed
$/ = '>'; # Set input record separator
while ( <INFILE> ) { chomp; next unless s/^s*(S+)//; my $name = $1; my @char = ( /[acgt]/g, ( '-' ) x $len )[ 0 .. $len - 1 ]; print OUTFILE " @char $namen"; }
close INFILE; close OUTFILE;
__END__
John |
John W. Krahn
Aug 31 2003, 03:10 PM
[ Top-posting fixed ]
Mike Robeson wrote:
QUOTE |
In article <[Email Removed]>, [Email Removed] (John W. Krahn) wrote:
You keep changing the specs Mike. :-) Based on your code and data above, this will work:
#!/usr/bin/perl use warnings; use strict;
print "Enter the path of the INFILE to be processed: "; chomp( my $infile = <STDIN> ); open INFILE, $infile or die "Can't open $infile for input: $!";
print "Enter in the path of the OUTFILE: "; chomp( my $outfile = <STDIN> ); open OUTFILE, ">$outfile" or die "Can't open $outfile for output: $!";
print "Enter in the LENGTH you want the sequence to be: "; my ( $len ) = <STDIN> =~ /(d+)/ or die "Invalid length parameter";
print OUTFILE "R 1 $lennn"; # The top of the file is supposed
$/ = '>'; # Set input record separator
while ( <INFILE> ) { chomp; next unless s/^s*(S+)//; my $name = $1; my @char = ( /[acgt]/g, ( '-' ) x $len )[ 0 .. $len - 1 ]; print OUTFILE " @char $namen"; }
close INFILE; close OUTFILE;
__END__
Yeah, the parameters keep changing because my buddy and I had incorrectly remembered the format it was supposd to be (several times).
|
If you think it's hard on your end, the only data I can test on is the
data you post here. :-)
QUOTE |
Sorry about that. Anyway, what you provided did work with some changes. the code you sent didn't do anything other than give me the command promt again - but I managed to get it to work anyway. However, I can't seem to figure out why I cannot use this line:
my @char = ( split( // ), ( '-' ) x ( $len - length ) );
|
split( // ) returns a list of ALL the characters in $_ and the use of
length() assumes that ONLY valid characters are in $_
QUOTE |
instead of this line:
my @char = ( /[a-z]/ig, ( '-' ) x $len )[ 0 .. $len - 1 ];
|
/[acgt]/g returns a list of ONLY the characters 'a', 'c', 'g' and 't'
and using the list slice assumes that there may be invalid characers in
$_
QUOTE |
in the script - I get errors ( I mean there are other changes that need to be made but these lines are my major focus). I just like the way the first line of code calculates the amount of dashes to add. It's just an aesthetic thing. :-)
|
It works fine if you KNOW that ONLY valid characters are in $_.
QUOTE |
Note I changed it to a-z because we use many other characters than "atcg", for example "n" means "unkown base". Also, just do not understand as clearly the second line of code above as I do the first. From what I can gather you are making, say, 50 dashes and then "filling in" the dashes that match the charatcers within [a-z] from left to right as long as there are characters to "fill in" the dashes. Does that make sense?
|
//g creates a list of valid characters from $_ with $len hyphens
appended on the end and that list is sliced to the length of $len.
QUOTE |
Anyway, when I add "$/ = '>';" to the original script below I get a ^^^^^^^^^^^^ |
I see no script below.
QUOTE |
contatination error (why?). Basically, I am trying to understand why
|
Did you chomp the input? Did you test for valid data before processing
it?
QUOTE |
certain bits of code "break" the script and others don't. I find I learn things better by trying alternate forms of code to figure out relationships. However, I have been looking through my perl books like crazy and can't seem to understand some of these relationships. I know it will take time and experience... I guess I'll pick up another perl book that provides another perspective.
Sorry about taking so long with this, I am trying to make an honest effort to learn. :-)
|
No problem. :-)
John
--
use Perl;
program
fulfillment
Kevin Pfeiffer
Aug 31 2003, 10:20 PM
In article <[Email Removed]>, Alan C. wrote:
[...]
QUOTE |
print @foodlist, "nn"; print "$foodlist[0]n"; print "$foodlist[1]n";
# hmm, @foodlist prints without space between each word; I not sure how to get a space put back in between each word there.
|
One "quick and easy way":
print "@foodlistnn";
--
Kevin Pfeiffer
International University Bremen
Paul Johnson
Sep 1 2003, 08:01 AM
Kevin Pfeiffer said:
QUOTE |
sub speak { my $either = shift; if (@_) { # something to say my $dialogue = shift; print $either->name, " says, "$dialogue"!n"; } else { print $either->name, " goes ", $either->sound, "!n"; } }
print $john->speak("Hello");
This works fine except...
sputnik:~/-> ./animals John says, "Hello"! 1sputnik:~/-
You'll see there is a "1" after the 'speak' routine's output (each time). I can't see where the "1" comes from.
|
Your speak method prints something and returns true if it is successful
(the print being the last statement in the method so its return value is
returned from the method). You then print that value, which happens to be
1.
--
Paul Johnson - [Email Removed]
http://www.pjcj.net
Paul Johnson
Sep 1 2003, 09:05 AM
[Email Removed] said:
QUOTE |
if you do: perl -e '$a="beta"; *$a=sub{print("")}; beta()' works and print ""
if you do: perl -e 'use strict; my $a="beta"; *$a=sub{print("")}; beta()' don't works
Who do I resolve this problem
|
Don't use strict.
Or more specifically, don't use strict refs.
The strict pragma is there to tell you when you are doing something that
might be a mistake. If it's not a mistake, don't ask strict to complain
when you do it.
There are ways that you can do what you want with strict in force, but why
bother. You can turn off strict refs just for the part of your program
where you don't want it. Don't make your life and your programs harder
than they need to be.
--
Paul Johnson - [Email Removed]
http://www.pjcj.net
Kevin Pfeiffer
Sep 1 2003, 01:14 PM
In article <[Email Removed]>, Paul
Johnson wrote:
QUOTE |
Kevin Pfeiffer said: [...] You'll see there is a "1" after the 'speak' routine's output (each time). I can't see where the "1" comes from.
Your speak method prints something and returns true if it is successful (the print being the last statement in the method so its return value is returned from the method). You then print that value, which happens to be 1.
|
print $kevin->cries_out("Aaaaaaaahhhhh...")
~/-> "Aaaaaaaaaaahhhhh..."
~/-> 1
(And he runs off into the street screaming and hitting himself on the head)
Thanks, Paul! :-)
--
Kevin Pfeiffer
International University Bremen
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
Danny Miller
Sep 1 2003, 03:00 PM
As long as the format of what you want (file.txt) remains the same you
could do the following:
($stuffattheend) = $string =~ //(w+.w+)$/;
Danny
-----Original Message-----
From: [Email Removed] [mailto:[Email Removed]]
Sent: Monday, September 01, 2003 11:41 AM
To: Perl Beginners
Subject: cutting a string
What is the function of cutting a string from a point until the last
character?
For example
$string="C:/progra~1/directory1/directory2/file.txt";
i want to find the last backslash (/) of the string and keep the
sequence
following it (file.txt)
Is it simple?
I tried with the split function but it returns a list.
I just want a scalar!
--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
David Wall
Sep 1 2003, 10:55 PM
--On Monday, September 01, 2003 2:53 PM -0700 "Randal L. Schwartz"
<[Email Removed]> wrote:
QUOTE |
"Trent" == Trent Rigsbee <[Email Removed]> writes:
Trent> Hi! I've completed "Beginning Perl" by Simon Cozens. What do you Trent> recommend as my next book? I'd like to tackle "Networking Programming Trent> with Perl" by Lincoln Stein or "Win32 Perl Scripting" by Roth but I'm Trent> not sure if I'm ready for these. Should I go for something like Trent> "Learning Perl" or "Programming Perl" before I learn sockets and Win32 Trent> or is it ok to go for it? Thanks!
Well, for the obvious reasons, I recommend Learning Perl followed by Learning Perl Objects References and Modules.
: -)
|
Even though you're obviously biased <g>, it's still a good route. I liked
"Learning Perl Objects References and Modules" because it gave a systematic
treatment of stuff I had picked up in bits and pieces. I'd recommend LPORM
because it has necessary knowledge for understanding the code in Stein's
networking book.
"The Perl Cookbook" is another excellent resource for picking up useful
techniques.
--
David Wall
Ned Cunningham
Sep 2 2003, 03:51 PM
Funny you just caught me working on something similar, and I have modified
this code for my purposes. This should lead you in the right direction!
Snip
#!/usr/bin/perl
use Win32::Console;
$StdIn = new Win32::Console(STD_INPUT_HANDLE);
my $Password = "";
$StdIn->Mode(ENABLE_PROCESSED_INPUT);
print "Enter Password: ";
while (my $Data = $StdIn->InputChar(1)) {
if("r" eq $Data ) {
last;
} elsif ("ch" eq $Data ) {
if( "" ne chop( $Password )) {
print "ch ch";
}
next;
}
$Password .=$Data;
print "*";
}
print "n $Passwordn";
<STDIN>
#note take out this print so it doesn't display to the user;)
Ned Cunningham
POS Systems Development
Monro Muffler Brake
200 Holleder Parkway
Rochester, NY 14615
(ext. 310
[Email Removed]
-----Original Message-----
From: Anbu Pugaleesan [mailto:[Email Removed]]
Sent: Tuesday, September 02, 2003 11:11 AM
To: Beau E. Cox
Cc: [Email Removed]
Subject: Re: Hide password in MS DOS
Hi Beau,
I would wish to have a code snippet using Win32::Console, becoz
this module
is available with me,
Else I may need to install Term::ReadKey.
-anbu
____________________________________________________________________________
_______
mailto:[Email Removed]
"Beau E. Cox" wrote:
QUOTE |
> ----- Original Message ----- > From: "Anbu Pugaleesan" <[Email Removed] > To: <[Email Removed] > Sent: Monday, September 01, 2003 7:18 PM > Subject: Hide password in MS DOS > > Hi all, > > I need to hide the password from STDIN while the user is keying. > > In unix I have an option like 'stty -echo', but any suggestion in doing > > the same in MS-DOS. > > thanks, > > anbu ____________________________________________________________________________ > _______ > > mailto:[Email Removed] > Hi - > Win32::Console works well for this. I can post > a snippet of how it used it (for hiding passwords) > if you wish. > Aloha => Beau; > == please visit == > <http://beaucox.com> => main site > <http://howtos.beaucox.com> => howtos > <http://PPM.beaucox.com> => perl PPMs > <http://CPAN.beaucox.com> => CPAN > == thank you ==
|
_______________________________________________
ActivePerl mailing list
[Email Removed]
To unsubscribe:
http://listserv.ActiveState.com/mailman/mysubs
Rob Hanson
Sep 2 2003, 04:03 PM
Something like this should work...
my $domain = 'www.station.fire.org';
if ($domain =~ /([^.]+.[^.]+)$/) {
print "$1n";
}
else {
print "Failed to find domainn";
}
This is very lenient in the matching, so it should match all valid domain
names as well as a lot of invalid ones. If there is the possibility of
invalid domain names (ie. "this is not a domain.name") you will need
something stronger.
Rob
-----Original Message-----
From: perl [mailto:[Email Removed]]
Sent: Tuesday, September 02, 2003 12:54 PM
To: [Email Removed]
Subject: base domain parsing www.mydomain.com
Please help me parse this www.mydomain.com to just mydomain.com
Below are some scenarios in which all I want is the last two values,
mydomain.com :
mydomain.com = mydomain.com
www.yourdomain.com = yourdomain.com
www.station.fire.org = fire.org
results in just the base domain.
thanks
--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
Ned Cunningham
Sep 2 2003, 04:07 PM
I am sure there are way better ways, in my case I am using the base load of
Perl. I have over a 1000 computers with this same load that I need to be
able to update and Win32::Console is loaded already. I wish I had TK loaded
but I don't, so I use what I have :-)
I just happened to be walking through Dave Roth's WIN32 Perl programming in
the section on console, so I thought I would give it a shot.
Sorry if I mislead anyone, still a newbie:(
Ned Cunningham
POS Systems Development
Monro Muffler Brake
200 Holleder Parkway
Rochester, NY 14615
(ext. 310
[Email Removed]
-----Original Message-----
From: [Email Removed] [mailto:[Email Removed]]
Sent: Tuesday, September 02, 2003 1:01 PM
To: Ned Cunningham
Subject: RE: Hide password in MS DOS
Why don't you use the Term::ReadKey?
I thinks that it does the some job!
Quoting Ned Cunningham <[Email Removed]>:
QUOTE |
> Funny you just caught me working on something similar, and I have modified > this code for my purposes. This should lead you in the right direction! > Snip > #!/usr/bin/perl > use Win32::Console; > $StdIn = new Win32::Console(STD_INPUT_HANDLE); > my $Password = ""; > $StdIn->Mode(ENABLE_PROCESSED_INPUT); > print "Enter Password: "; > while (my $Data = $StdIn->InputChar(1)) { > if("r" eq $Data ) { > last; > } elsif ("ch" eq $Data ) { > if( "" ne chop( $Password )) { > print "ch ch"; > } > next; > } > $Password .=$Data; > print "*"; > } > print "n $Passwordn"; > <STDIN > #note take out this print so it doesn't display to the user;) > Ned Cunningham > POS Systems Development > Monro Muffler Brake > 200 Holleder Parkway > Rochester, NY 14615 > (ext. 310 > [Email Removed] > -----Original Message----- > From: Anbu Pugaleesan [mailto:[Email Removed]] > Sent: Tuesday, September 02, 2003 11:11 AM > To: Beau E. Cox > Cc: [Email Removed] > Subject: Re: Hide password in MS DOS > Hi Beau, > I would wish to have a code snippet using Win32::Console, becoz > this module > is available with me, > Else I may need to install Term::ReadKey. > -anbu > ____________________________________________________________________________ > _______ > mailto:[Email Removed] > "Beau E. Cox" wrote: > > ----- Original Message ----- > > From: "Anbu Pugaleesan" <[Email Removed] > > To: <[Email Removed] > > Sent: Monday, September 01, 2003 7:18 PM > > Subject: Hide password in MS DOS > > > > Hi all, > > > > I need to hide the password from STDIN while the user is keying. > > > In unix I have an option like 'stty -echo', but any suggestion > in doing > > > the same in MS-DOS. > > > > thanks, > > > anbu > > ____________________________________________________________________________ > > _______ > > > > mailto:[Email Removed] > > > Hi - > > > Win32::Console works well for this. I can post > > a snippet of how it used it (for hiding passwords) > > if you wish. > > > Aloha => Beau; > > == please visit == > > <http://beaucox.com> => main site > > <http://howtos.beaucox.com> => howtos > > <http://PPM.beaucox.com> => perl PPMs > > <http://CPAN.beaucox.com> => CPAN > > == thank you == > _______________________________________________ > ActivePerl mailing list > [Email Removed] > To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs > -- > To unsubscribe, e-mail: [Email Removed] > For additional commands, e-mail: [Email Removed] |
Rob Hanson
Sep 2 2003, 05:19 PM
Use "eq" (as well as lt, gt, ne, ge, le, cmp) for string matching. The
operators "==" (as well as <, >, !=, >=, <=, <=>) for numeric matching.
Perl will convert the values based on the operator used.
So with "==", like you are using, Perl converts both arguments to numbers
before comparing.
So this is what you want...
$mystr eq "exactstr"
Rob
-----Original Message-----
From: rkl [mailto:[Email Removed]]
Sent: Tuesday, September 02, 2003 2:12 PM
To: perl
Subject: exact string match?
How to test for exact string match?
this doesn't work:
$mystr == "exactstr"
thanks
-rkl
--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
James Edward Gray II
Sep 2 2003, 01:41 PM
On Sunday, August 31, 2003, at 10:00 PM, Trent Rigsbee wrote:
QUOTE |
Hi! I've completed "Beginning Perl" by Simon Cozens. What do you recommend as my next book? I'd like to tackle "Networking Programming with Perl" by Lincoln Stein or "Win32 Perl Scripting" by Roth but I'm not sure if I'm ready for these. Should I go for something like "Learning Perl" or "Programming Perl" before I learn sockets and Win32 or is it ok to go for it? Thanks!
|
You've already got some solid suggestions about what books to read
next, so I'll add a different sort of comment. I'm not familiar with
where exactly "Beginning Perl" leaves off, and I'm not familiar with
"Win32 Perl Scripting". I do know "Network Programming with Perl"
pretty well though.
Stein's book is very good in my opinion and it guides you pretty well.
It starts with the basics and builds up to the tricky stuff. While it
does use some objects in places, I don't even think you have to know
too much about objects to understand what he's doing. He describes all
serious programs line by line anyway. It's also very cross platform,
so it'll work fine on Windows without reading extra books. Given all
of that, you might go ahead and jump right into it.
Only you can say how comfortable you feel with Perl at this point.
What you intend to do with sockets could be a big factor too, depending
on how complex it is. In the end though, the only way to gain some
serious programming skill is by programming. Reading a hundred books
alone will not teach you Perl, not that I have anything at all against
Perl's very rich library.
So, if you feel like you're progressing well and you want to try some
basic socket programs, I say give it a go. You'll learn what you want
and improve your Perl at the same time. You already even know a great
place to go get some help when you get stuck. Good luck.
James
Rob Hanson
Sep 2 2003, 08:49 PM
I run into this a lot. There is JavaScript in the page, and you need to
emulate that in your script.
Look at the source HTML for the page. It takes the password and look like
it Base 64 encodes the password, then sets a hidden form field named
"encoded_pw" to the value. It then clears the password field before sending
the data.
You need to emulate this process in your script. After that I would think
it would work.
Rob
-----Original Message-----
From: Pablo Fischer [mailto:[Email Removed]]
Sent: Tuesday, September 02, 2003 5:17 PM
To: [Email Removed]
Subject: WWW::Mechanize and Cookies
Hi!
Im creating an script that checks for broken links. Im using this modules:
use WWW::Mechanize;
use HTTP::Cookies;
What Im trying to do?, I need to login in a website (cause to check broken
links I need to be loged).
I also checked the cookies once I've loged and they're created, however,
when
I try to entrer another website I cant cause the website shows me a pretty
message: "Not Authorized".
My Code:
____________________
#El archivo en el que se guardan las cookies
$cookies = "/home/unmada/cookies.txt";
#El objeto que va a estar escuchando las cookies
$cookie = HTTP::Cookies->new(
file => $cookies,
ignore_discard => 1,
autosave => 1);
#$agent->cookie_jar($cookie);
#El objeto que va a hacerla de navegador
my $agent = WWW::Mechanize->new(agent => 'Mozilla/5.0',
debug => 1);
#La direccin que se va a visitar (la primera)
my $url = "http://cursos.itesm.mx/webapps/login";
#$agent->redirect_ok();
#Decirle al navegador que las cookies van a ser guardadas en el objeto
cookie
$agent->cookie_jar($cookie);
#Cargamos la pgina
$agent->get($url);
#Mostramos el titulo de la pgina
print $agent->title(),"n";
#Buscamos el formulario que tiene el nombre de 'login'
$agent->form("login");
#Llenamos el campo de user_id
$agent->field("user_id", "username");
#Llenamos el campo de password
$agent->field("password", "password");
#Le damos ENTER
$agent->submit();
Then to enter another website (in the same domain), I jsut:
$agent->get("otherurl_of_the_same_domain");
____
Thanks!
Pablo
--
Pablo Fischer Sandoval ([Email Removed])
http://www.pablo.com.mxhttp://www.debianmexico.orgGPG FingerTip: 3D49 4CB8 8951 F2CA 8131 AF7C D1B9 1FB9 6B11 810C
Firma URL:
http://www.pablo.com.mx/firmagpg.txt--
To unsubscribe, e-mail: [Email Removed]
For additional commands, e-mail: [Email Removed]
James Edward Gray II
Sep 2 2003, 06:24 PM
On Tuesday, September 2, 2003, at 02:19 PM, JOHN FISHER wrote:
QUOTE |
I have been using the split command happily for awhile, spliting up based on commas and tildes. However, I had a problem with a new file and noticed my script had created extra fields. If you have a file like this:
"Washington, George",909,"Abraham Lincoln",-100.00, "$10,500"
How can I appropriately split it so I will have 5 fields instead of 7? Doesn't appear the split command has this ability. My workaround has been to write a script to blank out commas between quotes, but that is not a good solution. It forces me to find a way to put the comma back after I split it which is efficient.
|
Text::CSV_XS from the CPAN will do all the work for you. I use it all
the time.
James
Rob Richardson
Sep 3 2003, 09:04 AM
Greetings!
I uploaded a set of Perl files to the target server and then started my
application. I got an error message immediately claiming that it
couldn't find one of my module files in @INC, and then it told me what
@INC was. The last entry in it was ".", which represents the current
directory. I'm pretty durn sure I put all the files into the same
place. So, I'd like to know what the host computer thinks "." is. How
can I retrieve the name of the directory "." points to?
Thanks very much!
Rob
__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com
Christiane Nerz
Sep 3 2003, 11:56 AM
Oh-oh - there was a mistake - I tried chomp, not chmod..
How do I use chomp correctly? I have an array of strings, want to cut
off the last n in each line and use the rest of the line. (concatenate
it to another string)
Jane
QUOTE |
Hi all!
I like to read several rows out of two different table-files and put them successively in a new file by:
@ergebnis_alles[$#ergebnis_alles+1] = @whole_data1[$l] . $whole_data2[$m];
Anything works fine, except that I can't delete the ending newline in the lines in the first tables. So the data is put in two following lines and not successively in one line. I tried chmod, but got error-messages.
Whole part of code is: foreach $el1 (@strings1) { $m=0; foreach $el2 (@strings2) { if ($el1 eq $el2) {@strings3[$#strings3+1] = $el1; @ergebnis_alles[$#ergebnis_alles+1] = @whole_data1[$l] . $whole_data2[$m]; } else {..... } $m=$m+1; } $l=$l+1; }
greetings Jane
|
Oh-oh - there was a mistake - Itried chomp, not chmod..