Re: form generator Perl... (The Holy Grail)
Pat Rice wrote: Hi all I'm wondering whats the best tool (preferably) open source, To use to generate HTML forms in Perl that I can link in to a database after, with optimistically code that is generated in a readable way. The holy grail would be: - type out the form names for each value. - press the button or run the script and out comes Perl and/or HTML - give me place holders for a database connection Ideally I can see this web app being session based, so any ideas greatly appreciated. I suppose I don't ask for much ! Thanks in advance Pat You may want to look at Rose::HTML::Objects and Rose::DB::Object... I've used the latter, not the former. http://search.cpan.org/~jsiracusa/ HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: how to send a page and a file at a download script?
shnaxe wrote: dear readers, i recently finished a small perl-cgi download script that sends files after some checks and logging. i call this script through a link on a static html-page and pass the file-id as a parameter. this all works nice so far, the part where i'm stuck at is that with clicking on the link, the page containig the link is replaced by a white blank page. i wonder how i could instead get either: - the page containig the link stays, link is targeted to a new window (minimal version) - a new page is displayed containg something like 'thank you for downloading... you download should start now...' (deluxe solution) for the minimal version, i thought putting a simple 'target=_blank' into the link should do what i want (only tested with firefox 3.0 so far). this indeed works, but the focus changes to the popping up new blank tab and further, this tab stays open after the file is transferred. i remember having seen this differently on the web. for the deluxe verson i think i somehow need to send out two headers, one of type 'application/x-download' (for the file) and another of type 'text/html' (for the page). but how would i do this? i'm afraid that the second header (whichever) will not get recognized as a second document but be embedded into the first. i guess a short sleep between the first and the second header won't do it... You shouldn't really need a new window at all if you don't want one, at least not in some browsers. If you return the proper headers followed by the content then the user should be able to click the download link and stay right where they are with the standard browser action occuring. If you return a proper content-type then the browser should just do what you want, if you return a Content-Disposition header then you will get to specify a suggested filename, etc. 'application/octet-stream' can usually be used as a generic download header if you don't have a specific content-type in mind. So your headers might be: Content-Type: application/octet-stream Content-Disposition: attachment; filename=some download.pdf or in the above case if you know it will be a PDF, Content-type: application/pdf thanks for help and suggestions in advance, regards, shnaxe HTH, http://danconia.org ps: well, i am unsure if this would have been better posted to another group (but which) since its maybe not a pure perl-question. i got to admit that from my point of knowledge, the solution to the problem i described seems to be somewhere on a blurry line between perl/cgi and html... I'd say it is appropriate. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: parsing a line
thunder wrote: Hello all I have the following small file that i am parsing one line at a time (each line consists of hex values) line 1: 0d line 2: line 3: 2000 line 4: 0064 line 5: 76d457ed462df78c7cfde9f9e33724c6 line 6: bded7a7b9f6d763e line 7: 0059010081bb300597603b6f90ef4421 line 8: 001608427754e957a0d281bb30059760 line 9: a72f731c3be6 For line 5, for example, i want to break it up into chunks of 8 hex charaters (ie for example 76d457ed, 462df78c etc). I tried to use the shift operator (ie or ) but perl gives an error. Any help with the above would be appreciated. Thanks Check out the pack/unpack functions, perldoc -f unpack http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Extracting TD's from a Text File (Regex Help).
[EMAIL PROTECTED] wrote: TEXT FILE ## td class=PhorumTableRowAlt thread style=padding-left: 0px a href=http://mysite.com/link/here_goes?id=239;LINK/a nbsp;span class=PhorumNewFlag/span/td td class=PhorumTableRowAlt nowrap=nowrap width=150 a href=http://mysite.com/link/here_goes?id=239;LINK/a /td td class=PhorumTableRowAlt PhorumSmallFont nowrap=nowrap width=15006/11/2007 12:29AM /td /tr The text file contains hundreds of tds structure like above. All I need is to extract the td with class PhorumTableRowAlt thread. I have tried every possible option, but finally I am coming to you for any Regex for it? TIA. HERE IS WHAT I AM DOING: pen(TXT, links.txt) or die Unable to open file; my @links = TXT; close (TXT); foreach my $link(@links) { if ($link =~ m|td class=PhorumTableRow thread style=padding-left: 0px(.*?)/td|gsi) { print $1;} } But NOTHING coming up. No results. Thanks for any help. Sara. Parsing HTML with regexes is just a bad idea. Try a module from CPAN, I've had good luck with HTML::TokeParser::Simple, http://search.cpan.org/perldoc?HTML::TokeParser::Simple http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Adding a comma to format localtime
Gregg O'Donnell wrote: All, I use this line of code: my $datetime = join ' ', (split ' ', localtime)[0,2,1,4,3]; my $localtime = [ split ' ', localtime ]; my $datetime = $localtime-[0] . ', ' . join ' ', @$localtime[2,1,4,3]; TMTOWTDI... http://danconia.org To create this result: Mon 9 Apr 2007 09:15:05 How can I add a comma to this result to get: Mon, 9 Apr 2007 09:15:05 Best and thanks, Gregg -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Tweeking a sendmail routine.
Greg Schiedler wrote: I know enough Perl to be dangerous! I have a form that sends out several different confirmations depending on who the receipient is. One particular E-mail I need to be in html format so I can put it into a specific format. I added a couple of lines to the sendmail routine I was using and it fixed my E-mail problem but created a problem with my fax gateway copy. #1 gets sent the Joe Enduser plain E-mail(Can be html my tweek forced html) #2 gets sent to the Office HTML Format. #3 Fax gateway (Plain E-mail). Fax gateway is in the US Telephone format ie. [EMAIL PROTECTED] I thought about adding an if statment but it looks like if I added an if/else to my tweeked else statement the receipient info has already been sent Greg :-) Best suggestion would be to switch to using a module. MIME::Lite for instance but there a lot that will work. Check CPAN. Mail while it seems simple is incredibly complex, re-inventing the wheel, especially with such strict requirements is going to be time consuming. http://danconia.org file: sendmail.pl snip # Give the server the message header print SMTP DATA$CRLF; sysread(SMTP, $_, 1024); if (!/[^0-9]*354/) { $Error_Message = $_; return(6) } print SMTP To: @to$CRLF; print SMTP From: $from$CRLF; print SMTP CC: @cc$CRLF if $cc; print SMTP Subject: $subject$CRLF; # If there are mime files to attach, we need special headers. if ($mime_id) { print SMTP x-sender: $from$CRLF; print SMTP x-mailer: CGI/Perl Cookbook$CRLF; print SMTP Mime-Version: 1.0$CRLF; print SMTP Content-Type: multipart/mixed; boundary=\$mime_id\$CRLF$CRLF; print SMTP --$mime_id$CRLF; print SMTP Content-Type: text/plain; charset=\US-ASCII\$CRLF$CRLF; } # Greg @ Limo.Net 01/24/2007 # Added two header lines for force HTML output. # else { print SMTP $CRLF } # else { print SMTP Mime-Version: 1.0$CRLF; print SMTP Content-Type: text/html; charset=\ISO-8859-1\$CRLF$CRLF; } # End Greg @ Limo.Net 01/24/2007 # Output the message body. if ($body) { if (!($body =~ /^[\\\/:]/) ($body =~ /\s/)) { print SMTP $body } elsif (-e $body -T $body) { parse_template($body, *SMTP) } } print SMTP $CRLF; # Attach each file. for ($i = 0; $i @ATTACH_FILES; ++$i) { $attach_file = $ATTACH_FILES[$i]; $encoding = $ENCODING[$i]; # Split the filename by directories. / for unix, \ for dos, : for mac /snip Scanned for Virus by http://Barracuda.Limo.Net -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: CPAN installs
Kevin Viel wrote: I am attempting to install modules on a Solaris v10 computer for which I do not have root privileges. I see in MyConfig.pm that the build directory is local: 'build_dir' = q[/home/kviel/.cpan/build] Where does it install the (built) module? Thank you, Kevin The build_dir doesn't mean a lot in this case, assuming you are asking what I think you are asking. Instead you want to specify an install location in the makepl_arg and or mbuildpl_arg settings. For instance, makepl_arg = LIB=~/local/lib PREFIX=~/local/lib mbuildpl_arg = --install_base /home/user/local/lib Check perldoc CPAN for information about 'o conf'. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Formatting/presenting regex
Owen wrote: I have this regex to look at an Apache log. There are modules to help with that task on CPAN. m/^(\S+) \S+ \S+ \[(\d{2})\/(\S+)\/(\d{4}):.+\] (\w+) (\S+) ([^]+) (\d{3}) (\d+|-) .+$/; Would like to set it out in a bit more readable form a la Perl Cook Book and others eg m/ ^(\S+) # Comment \S+# Comment \S+# Comment etc, but they don't work and I suspect it is something to do with the spaces between the elements. I have even tried specifying spaces with \s The key is to use the /x modifier on the end of the regex to allow this type of formatting. You then, according to perldoc perlretut, can either backslash real spaces or put them in a character class. See, perldoc perlretut for more. Can someone give me a pointer as to how to go about this. HTH, http://danconia.org TIA Owen -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Negate a regular expression
Mathew Snyder wrote: Ken Foskey wrote: On Fri, 2006-12-29 at 23:36 -0500, Mathew Snyder wrote: I'm trying to set up an if clause to exit if an answer given is anything but either any case combination of 'y' or 'yes'. This is what I have: exit if $ans =~ m/[^y|^yes]/i; exit if $ans =~ m/^(y|yes)[ \t\r\n]*$/i; The brackets are a group, square brackets are a character class. It is probably a good idea to ignore whitespace around the error as well. Let me clarify though. I have a script that will grab a bunch of emails which need to be deleted from a database and displays them. I then want it to ask if the user wishes to delete them. I want 'No' to be the default so that anything other than any case combination of 'y' or 'yes' will cause the script to exit. This includes simply hitting 'enter' or entering anything that ISN'T 'y' or 'yes', case notwithstanding. So having the regex look also for whitespace characters will defeat this goal. So how do I negate this if classes aren't the proper way to go? If you want to be so explicit, why not be explicit... exit unless (lc $ans eq 'y' or lc $ans eq 'yes'); http://danconia.org Mathew -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: -e question
Lou Hernsen wrote: I use the -e to check to see if a file is present if (-e $Pics/$Game{Page}.jpg) { } Question I can get it to work looking for .pl and .gif but not .jpg I have checked all the directorie vars and even did this print qq|img border=0 src=$Pics/Camera.gif width=$Game{CameraW} height=$Game{CameraH}BR|; print qq|BR|; print qq|a target=$Game{Page} href=$Pics/$Game{Page}.jpg|; print qq|img border=0 src=$Pics/Camera.gif width=$Game{CameraW} height=$Game{CameraH}BR|; print qq|/a|; print qq|BR|; if (-e $Pics/$Game{Page}.jpg) { print qq|img border=0 src=$Pics/Camera.gif width=$Game{CameraW} In the above line do you mean to have '.jpg'? height=$Game{CameraH}BR|; } I get the first two images but not the last one.. so I know i have the dirs correct are .jpg's not -e able??? -e cares not and knows not of the type of file. yeah.. i'm nonprofessional hobbiest my style suck... can someone answer the question, please? Helps? http://danconia.org Lou -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: trouble with meta http-equiv
David Bear wrote: I'm trying to put a client side redirect with http-equiv refresh. I'm using the syntax: my $req = CGI-new(); print $req-header( text/html ); print $req-start_html( -head=meta({-http-equiv = 'refresh', In the above line the call to meta() is a function call, but you have started out with the object syntax. So you likely haven't imported any of the function lists, so you either need to import the correct list, or switch to the object syntax, $req-meta(...) -content = '1;URL=' . $req-refere()})); Note you probably need $req-referer in the above line... HTH, http://danconia.org but I get an error: Undefined subroutine %main::meta called This seems to be what is documented on cpan. I must be missing something simple. Any ideas? -- David Bear College of Public Programs at Arizona State University -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Best book to update XML via Perl?
C.R. wrote: Hi, I have Perl 5.6.0 on Solaris, and on DOS. We have an XML document that has many prices in it that need to be changed. They are keyed by part number, and each part has a price grade, each grade has a price. I know there are many tools that Perl can use to update XML. Which one is the most straight forward? XML::Simple is very straightforward and fairly simple to use. What book can I buy to learn this XML in Perl tool? ORA has one, but I would skip it. Mostly it covers how to use the modules much as the modules' documentation does. Start with the docs... I know Perl fairly well. Thanks. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Crypt::GPG won't decrypt file...rewrote it to use system, but only partially works
RICHARD FERNANDEZ wrote: I re-wrote the decryption routine to use system instead of Crypt::GPG, and came across another puzzle: my @gpg_command = (/usr/bin/gpg --decrypt $encrypted $decrypted 2 /dev/null); system(@gpg_command) == 0 or warn system @gpg_command failed: $!; works. It decrypts my file successfully. But if I break up the arguments like it says in the doco, like so: my @gpg_command = (/usr/bin/gpg, --decrypt, $encrypted, , $decrypted, 2 /dev/null); system(@gpg_command) == 0 or warn system @gpg_command failed: $!; it does not work. Instead I get a usage error. Could someone please explain where I've gone wrong? I would like to use Crypt::GPG instead of system, but I have to get this finished. Thanks! richf In my various attempts to get the gnupg related modules working on CPAN I came up with two options Crypt::OpenPGP which is in general slow because it attempts to do things in Perl, and GnuPG::Interface which worked almost perfectly but we were using it in a weird fork model kind of way, for doing a single encrypt/decrypt run at a time it worked brilliantly. Having said that, one caveat, my analysis was done in early 2003. I would suggest giving GnuPG::Interface a go because it handled calling out to 'gpg' most correctly. Meaning it uses the status-fd, logger-fd options properly which is the preferred way to call gpg in an automated fashion. Good luck, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How to manage around 1000 entries which will constantly be changing
Mr. Shawn H. Corey wrote: On Fri, 2006-31-03 at 15:45 -0800, Tom Phoenix wrote: You should loop over the input, pushing each item on to an array. If at any time you have 2000 items in the array, sort them and discard any you don't want to keep. $#data = 999 if $#data 999;# OBperl: one way to discard elements When you finish looping, sort-and-discard again. You'll never need more than 2N items in memory at any given time. Does that algorithm work for your needs? Sorting is not necessary. If he keeps an array of the best, that means lowest, records then all he has to do is compare every new entry with the highest. This is called fail early. This means, if it's going to fail, it should at the earliest opportunity. If it succeeds then it searches down thru the list, to find its place. This is called succeed early. Given that the procedure can flip between these two methods, it is faster than any sort. Unless the sort optimizes out the need to loop through so many elements, and/or is written at a lower level. If each new item that is entered goes in the last place then you have to loop over every element of the list every time. But a sort might be optimized not to have to do that. Your algorithm is essentially maintaining a sorted list, but doesn't really have an optimization applied to determine the new place. Only real way to tell would be benchmarking, but either should be a very good step in the right direction http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Expect script to install sshkey
Ramprasad A Padmanabhan wrote: Hi all, I have a perl Expect script that install rsa keys for ssh auto login. When I run the script on command line it works fine. Now when I run it inside a CGI the script simply gets stuck. I can see from the from the SSH server and also the expect logs that the login is happenning. But After login nothing happens :-( The commands I give to append the authorized_keys2 file are not executed at all. Are the keys readable by the web server user? Sounds like a permissions problem. http://danconia.org Can someone help me ? Thanks Ram -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Help: Math::Pari won't install
RICHARD FERNANDEZ wrote: I'm trying to build Math::Pari along the way to building Net::SFTP, but the make fails with the following error: pariinl.h: In function `mulssmod': pariinl.h:887: error: asm-specifier for variable `hiremainder' conflicts with asm clobber list pariinl.h:887: confused by earlier errors, bailing out make[1]: *** [es.o] Error 1 make[1]: Leaving directory `/s01/.cpan588/build/Math-Pari-2.010703/libPARI' make: *** [libPARI/libPARI.a] Error 2 Not sure what other information is relevant, but I'm doing this on a Solaris 8 box using: # gcc -v Reading specs from /usr/local/lib/gcc-lib/sparc-sun-solaris2.8/3.3.2/specs Configured with: ../configure --with-as=/usr/ccs/bin/as --with-ld=/usr/ccs/bin/ld --disable-nls Thread model: posix gcc version 3.3.2 Any help would be appreciated! richf This has lingered long enough without response. Sorry it took me a while to get back to it after initially seeing it. I had this same problem a couple of years ago. It does appear that Math::PARI has an active maintainer again so you might try dropping him a line about this issue. I solved it by testing each previous version (of libPARI) until I hit one that would install cleanly. As much as it stinks to not have the most recent version of something, a working version is better than no version. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Help: Math::Pari won't install
RICHARD FERNANDEZ wrote: Thanks for the response. I did manage to solve the Math::Pari install problem by following Jeff Eggen's idea about configuring it with machine=none. I have no idea about whether or not, as he mentions, it's unusably slow because I proceeded with the rest of the Net::SFTP install and got similarly hung up on the install for Math::GMP. (Un)fortunately enough time has elapsed on this that the Powers That Be decided to shelve this project and go a different way. So for now I'm off the hook. Ah, hmm... I had the same problem with Math::GMP, though determined that as long as you only want Protocol 2 it isn't really needed. So doing a force install on Math::GMP will get it past the testing on Net::SFTP. Sorry I couldn't be of much help sooner. Ironically, we have Net::SFTP running fine in other environments. It's just this one box... Thanks again for the help! No worries. richf http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Help With signals.
Leif Ericksen wrote: I am trying to set up a routine to trap signals so that I can pass it to a sub that will act on the signals and it does not seem to be functioning as I would think. SAMPLE: I will admit some of the code was taken from the camel book. :) I do have use strict on. my $name = \n; my $i = 0; defined $Config{sig_name} || die The Stupid System does not support Signals?; foreach $name(split(' ', $Config{sig_name})) { $Config::signo{$name} = $i; $Config::signame[$i] = $name; #print $name:$i \t = SIG{'$name'} = \sigcat\n; $SIG{'$name'} = \sigcat; In the above line you are single quoting $name so that it is not interpolated. HTH, http://danconia.org $i++; } Now I do have an while (1){}; setup so that I can test the break. Using the above code I do not seem to enter my sub sigcat I do not see my 'special' signal catch message if I press ^C. HOWEVER, if I add the following lines: $SIG{'INT'} = \sigcat; $SIG{'HUP'} = \sigcat; $SIG{'STOP'} = \sigcat; $SIG{'ABRT'} = \sigcat; $SIG{'TERM'} = \sigcat; It does break out and lets me know that it received a HUP. If I take the single quote ' off of the $name in the loop I get a segmentation fault so I guess I need the quotes. Can anybody tell me what is wrong with the loop and why it is not working? Also if I uncomment the line: #print $name:$i \t = SIG{'$name'} = \sigcat\n; Might want to examine the output more closely, $name should be being printed as $name rather than INT, HUP, etc. It appears to be running the correct set routine as in the 5 I have shown above. I know I must have something simple but I just can not see what it is... -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Help With signals.
Please bottom post... Leif Ericksen wrote: Actually not quite what you thought on the output... $ ./myt.pl ZERO:0 = SIG{'ZERO'} = sigcat HUP:1= SIG{'HUP'} = sigcat INT:2= SIG{'INT'} = sigcat QUIT:3 = SIG{'QUIT'} = sigcat ILL:4= SIG{'ILL'} = sigcat TRAP:5 = SIG{'TRAP'} = sigcat ABRT:6 = SIG{'ABRT'} = sigcat BUS:7= SIG{'BUS'} = sigcat FPE:8= SIG{'FPE'} = sigcat KILL:9 = SIG{'KILL'} = sigcat Ah yep missed the double quotes. Also if I use the double quote as opposed to a single quote in: SIG{'$name'} = \sigcat; The above should be: $SIG{$name} = \sigcat; $name can't be single quoted, and you have to call the SIG hash as a hash... http://danconia.org I get a like result it does not work as desired and a complete lack of quotes gives me a segmentation fault. On Fri, 2006-01-06 at 15:37 -0700, Wiggins d'Anconia wrote: Leif Ericksen wrote: I am trying to set up a routine to trap signals so that I can pass it to a sub that will act on the signals and it does not seem to be functioning as I would think. SAMPLE: I will admit some of the code was taken from the camel book. :) I do have use strict on. my $name = \n; my $i = 0; defined $Config{sig_name} || die The Stupid System does not support Signals?; foreach $name(split(' ', $Config{sig_name})) { $Config::signo{$name} = $i; $Config::signame[$i] = $name; #print $name:$i \t = SIG{'$name'} = \sigcat\n; $SIG{'$name'} = \sigcat; In the above line you are single quoting $name so that it is not interpolated. HTH, http://danconia.org $i++; } Now I do have an while (1){}; setup so that I can test the break. Using the above code I do not seem to enter my sub sigcat I do not see my 'special' signal catch message if I press ^C. HOWEVER, if I add the following lines: $SIG{'INT'} = \sigcat; $SIG{'HUP'} = \sigcat; $SIG{'STOP'} = \sigcat; $SIG{'ABRT'} = \sigcat; $SIG{'TERM'} = \sigcat; It does break out and lets me know that it received a HUP. If I take the single quote ' off of the $name in the loop I get a segmentation fault so I guess I need the quotes. Can anybody tell me what is wrong with the loop and why it is not working? Also if I uncomment the line: #print $name:$i \t = SIG{'$name'} = \sigcat\n; Might want to examine the output more closely, $name should be being printed as $name rather than INT, HUP, etc. It appears to be running the correct set routine as in the 5 I have shown above. I know I must have something simple but I just can not see what it is... -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sub args as pointers or values?
Bryan R Harris wrote: I remember from my C++ class that when you pass arguments to subroutines you can pass them either as a pointer to the real variable (so you modify the original if you change it), or as a copy (which you can change all you want and not affect the original). Is there a perl equivalent of both of those two concepts? - B perldoc perlsub Sort of is the short answer. Perl uses a sort of smart pass-by-reference. But unless you pass explicit references then if you assign the arguments to named variables then you have pass-by-value. The details are best found in the above docs. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Constant Hash problem
Kevin Old wrote: Hello everyone, I'm trying to define a constant hash and have the following: use constant STOPWORDS = map { lc $_ , 1 } qw(a about above across adj after); I do not get a hash from this. This does work, however: my %stopwords = map { lc $_ , 1 } qw(a about above across adj after); use constant STOPWORDS = \%stopwords; I'm wondering what I'm doing wrong in the first definition. The second is only sort of constant. It creates a constant reference to the hash, however the hash itself should still be editable which is not probably what you wanted. The problem is that constants are defined at compile time rather than run time. You might be able to accomplish both, using a BEGIN { } wrapper around the first. HTH, http://danconia.org Any help is appreciated! Kevin -- Kevin Old [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Subst string
MARG wrote: Hi, I'm trying to subst the string: # Include conf/extra/httpd-ssl.conf for Include conf/extra/httpd-ssl.conf with the command: perl -pi~ -e 's/# Include conf/extra/httpd-ssl.conf/Include conf/extra/httpd-ssl.conf/' /usr/local/httpd/conf/httpd.conf but i get an error. I've used this before with success. Is it because of the white space between Include and conf ? No, it is because the search string contains the same delimiter as the expression is using, aka the '/'. You need to either escape the / characters or change your delimiter, perl -pi~ -e 's{# Include conf/extra/httpd-ssl.conf}{Include conf/extra/httpd-ssl.conf}' /usr/local/httpd/conf/httpd.conf For instance, http://danconia.org Any help would be apreciated. Warm Regards, MARG -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: How do you determine if a file is a symlink?
RICHARD FERNANDEZ wrote: According to the docs, if you stat a symlink, you will get information for the target file, and lstat works on symlinks... I'm confused. How do you determine if a file is a symlink to begin with? TIA richf perldoc -f -l if (-l $file) { # file is a symlink } http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: running child processes
Octavian Rasnita wrote: Hi, Is it possible to create more child processes and let them run, but close the main program immediately? I have read (in perldoc perlfork) that: A way to mark a pseudo-processes as running detached from their parent (so that the parent would not have to wait() for them if it doesn't want to) will be provided in future. Thank you. Teddy I think the note above is for the special case when the parent still has work to do but doesn't want to have to wait on the children, which is subtly different than what you actually asked, aka can the parent close. Assuming you really do want to close the parent then you should be able to, though you may want to take a look at the source of, Proc::Daemon::Init() Before coding this yourself, it is a handy tool. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: reference assignment - lol
Dermot Paikkos wrote: Hi, I am a bit stuck with references and was hoping someone could help me out. In File1 I need to isolate the last number in the column and see if it exists in file2. If so, I would like to add the content of the line from file1 and print it out. There may be other ways of doing this but I wanted to try to do it with references as this is my current weak spot :-( Below is some sample data and my effort. What is happening with my current attempt is that it is simply looping through the 2nd file and printing the last assignment to the hashref. So I guess the problem is with the way I am creating the hashref rather then dereferencing it. You are not creating a list of lists. You only have a single hashref which is going to be set to the last line of the first file *always*. I am sure this is a simple problem. Can anyone offer a bit of assistance . I promise will do some more reading tonight. Thanx. Dp. my effort.pl == #!/bin/perl use strict; use warnings; Excellent start! my $file = file1.txt; my $file2 = file2.txt; Single quotes are fine above. my $in = 0; my $found = 0; my $hashref; Generally it is preferred to declare variables when we first use them rather than in a list at the top of the program. open(FH,$file) or die Can't open $file:$!\n; Nice, parens aren't needed around open above. while (FH) { chomp; my @f = split(/\t/,); next if ($f[3] =~ /NULL/i); if ($f[3] =~ /(p|s)\d{4}/i){ ++$in; my $num = uc($f[3]); my $rest = $f[0].\t.$f[1].\t.$f[2].\t; Are you actually meaning to assign $rest into the hashref below? And in either case the above can be written much more succinctly as, my $rest = $f[0]\t$f[1]\t$f[2]\t; Or using a join and array slice, my $rest = join \t, @f[0..2]; # print $num\n; $hashref = { 'number' = $num, 'rest' = $_, }; Right here you are continually clobbering $hashref. You need to be assigning to a list of hashes, for instance, $matches-{$num} = { 'number' = $num, 'rest' = $rest }; Assuming you want duplicates clobbered as well. } } close(FH); open FH2, $file2 or die Can't open $file2:$!\n; while (FH2) { chomp; next if ($_ !~ /(P|S)\d{4}/); (my $num) = ($_ =~ /\s(\w\d{4})/); print Comparing $num with $hashref-{'number'}\n; if (exists($hashref-{'number'}) ) { # print $hashref-{rest} $hashref-{'number'}\n; ++$found; } } close(FH2); print Done. Found $found / $in\n\n; I think what might help you the most is to improve your variable naming conventions. If you named your variables something other than 'hashref' for instance you might have caught the problems yourself. The first indication of the problem is that you have nothing named list_of or matched_numbers or part_numbers or temperatures, etc. Using generic names like file1/file2, hashref, f, num, etc. give no context about what the program is working on or does. When I see 'rest' I think, sleep 360; HTH, http://danconia.org [snip samples] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: aliasing a function
JupiterHost.Net wrote: Just a mental exercise :) What is the best way to alias a function, for instance: you can call it: sub say_it_loud( print @_ ); or use a type glob, etc What I'm trying to figure out is say you wanted to alias a function that is context sensitive? What I mean is say I wanted to have a function that is really carp but call it something else? carp oops; whine oops; and the whine is exactly like carp including the caller() point of view? perldoc -f goto I think the goto-NAME form does exactly what you asked for. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Parameterizing a module
[EMAIL PROTECTED] wrote: I see. Thanks Shawn. Since we are at it, would you mind explaining a little bit about the significance of our keyword. I have never understood it properly. Most books that I referred to say that it's a lexically-scoped global variable. What does that mean? I understand global variables to be the ones which are accessible to all perl program units (modules, packages or scripts). But then, what is so lexically-scoped about it? What do the perl compiler and opcode interpreter do when encounter a variable name prefixed by our? I do not mean to ask you so many questions at once. It is just to prove how confused I am about this keyword! Thanks. Vishal perldoc -f our perldoc vars Those should help. I think the key line is: The our declaration has no semantic effect unless use strict vars is in effect, in which case it lets you use the declared global variable without qualifying it with a package name. Additionally: http://perl.plover.com/FAQs/Namespaces.html In the above a variable tagged with 'our' is a Package Variable. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Parameterizing a module
[EMAIL PROTECTED] wrote: Hi all, I have a module which does nothing but include a bunch of use statements (Shawn Corey, I think you taught me how to do that).It looks like this: -- #PerlMQ.pm use strict; use warnings; use statement1; use statement2; use statement3; #and so on... 1; _END_ In my script, I load the module by saying use PerlMQ;. However, now I want to load only certain use statements from the module depending on the parameter I give it. For example, in my script, I want to say use PerlMQ qw(some_parameter) in order to load the use statements specified by some_parameter in the module. Is it possible to do that? Because 'use' happens at compile time rather than at runtime this is more difficult to accomplish then just wrapping them in an if statement for instance. One way to load modules based on conditions is to wrap the loading of the module in an Ceval EXPR statement. It would look something like, if (condition) { eval use module name; if ($@) { die Failed to load module name module at runtime: $@; } } You can then use the module as usual, however you must be certain that all calls to the module's subs are wrapped in a check to make sure they are available, or you need to make sure a replacement module did get loaded that handles the same calls. Basically don't call something that hasn't been loaded, which is the tricky part of loading or not loading a module. perldoc -f eval Most of the examples on the web seem to use the EXPORT package while providing the qw(some_parameter) functionality in the script. How do I do it in my module which seems pretty unconventional? That is for loading items into the symbol table (usually) from the particular module and can't really help you with runtime loading of modules. http://danconia.org Thanks Vishal This mail sent through www.mywaterloo.ca -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: OOP inheritance question (simple)
Ken Farmer wrote: I have tried this question in a couple of other places but the answers are far above my current level of understanding of oop - which is the level of very interested newbie - real newbie. So here goes again. I make an empty (of data) perl object1 with an included method which can be called to put data into the hash inside this object. I can now call that method and insert data. Simple OOP - it works. Now I make another empty object2 and inherit object1. I can call the inherited method from object1 through object2 and it also works, but not like I assumed it would. I am trying to understand whether... I have two identical and totally separate objects, each independent of the other with the second being a copy of the first plus whatever might be added later - but nothing in this case. Or I have two objects and the second one sees (or calls, or views) the first. It really doesn't matter except... The reason I am asking, is that the second object inherits the methods of object1, but doesn't inherit the data currently inside object1. If I call the add method in object1, ($object1-add_data) it adds data to object1. Since object1 is the parent that should be correct. But that new data doesn't appear to object2. In fact, object2 never sees data in object1 unless that data was put there by the new() constructor when the object was made. And calling the add method ($object2-add_data) doesn't add data to object1 - it adds it to object2. I think I see why by tracing through the process. When object2 inherits object1, it runs the initalize new() function of object1 and makes a new and empty object. I can't find any example in my books about how to inherit an object without having the constructor in the inherited object run. Or if it can be. Have I confused everybody? I am. So, is data inheritable? Or only methods? I doubt that is correct since it would take away a lot of reason for inheriting in the first place. OOP is a lot of fun and I can see where it would be great in a large project, but has a very steep start in the learning curve. CptKrf See the other posters responses as well, but I think it might help if you read through some docs on OOP programming, check out: perldoc perlboot perldoc perltoot perldoc perltooc And issuing, perldoc perl Will give you the full list of what is available. Additionally Learning Perl Objects, Refs, and Mods is an excellent book, as is the somewhat dated Object Oriented Perl. Good luck, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Parameterizing a module
Shawn Corey wrote: [EMAIL PROTECTED] wrote: In my script, I load the module by saying use PerlMQ;. However, now I want to load only certain use statements from the module depending on the parameter I give it. For example, in my script, I want to say use PerlMQ qw(some_parameter) in order to load the use statements specified by some_parameter in the module. Is it possible to do that? Yes, there are ways. -- #PerlMQ.pm use strict; use warnings; use statement1; use statement2; use statement3; # Change to: use File::Basename; use if ( basename( $0 ) eq 'script1' ), module1 = undef; use if ( basename( $0 ) eq 'script1' basename( $0 ) eq 'script2' ), module2 = undef; use if ( basename( $0 ) eq 'script3' ), module3 = undef; #and so on... 1; _END_ See `perldoc if` for details. Huh, very nice. Note that is a new pragma in Perl 5.8. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Parameterizing a module
Todd W wrote: [snip] you could do something like this: $ cat TestMod.pm use warnings; use strict; package TestMod; use Exporter; sub import { my $class = shift; foreach my $module ( @_ ) { require $module; } } 1; $ cat testrun.pl use warnings; use strict; use TestMod qw( CGI.pm LWP/Simple.pm ); print( UNIVERSAL::can( CGI = 'new' ), \n ); print( UNIVERSAL::can( 'LWP::Simple' = 'get' ), \n ); saying use Exporter; in your module means that when your module is use()ed by a client program, a function in your module named import will be called by Exporter if this import function exists. Heres the output of running that program: Just for your info, the call to 'import' has nothing to do with the use of Exporter. Exporter actually provides a special 'import' method that does fancy stuff, but the actual calling of 'import' happens *everytime* you do a 'use' (assuming the module 'can', aka has a sub named 'import') regardless of whether Exporter has been loaded. And to have this actually work you would have to inherit from Exporter so that 'import' can be found in the sub lookup. Though as you have shown you can also write your own import sub, which can be quite handy. perldoc -f use perldoc Exporter for more info. http://danconia.org $ perl testrun.pl CODE(0x818459c) CODE(0x8129448) which shows that after saying use TestMod qw( CGI.pm LWP/Simple.pm );, a package named CGI can new() and a package named LWP::Simple can get(). It should be pretty safe too, because require() will die if it cant find the module. I just made this up and I've never done anything like this before ( I program in mod_perl so I just use() everything I will ever need ), so there may be some caveats that aren't immediately obvious to me. Enjoy, Todd W. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: OOP inheritance question (simple)
Ken Farmer wrote: Wiggins d'Anconia [EMAIL PROTECTED] wrote: See the other posters responses as well, but I think it might help if you read through some docs on OOP programming, check out: perldoc perlboot perldoc perltoot perldoc perltooc And issuing, perldoc perl Thanks for the response, and the other responders as well. Believe me, I have not only read the above many times, but killed several trees and printed them out so I could refer to them. I agree that I need a perl object book. I am using standard perl books, all of which have a chapter on poop but obviously don't go into detail. In fact, part of the problem is the stuff that is left out is different in each book so some of the info appears to contradict the others. Plus, a non-perl object book will really lead a newbie out of the promised land - fast. I have ordered both of the available books on perl objects and am impatiently waiting for the delivery. The problem, I think, is that I have done procedural - based programming (as a hobby) for decades and in learning OOP I just haven't managed to make that mental shift yet. I had the same problem back in the '90's when I got my first event-based suite (VB or the like) and it bothered me for weeks that I didn't know what my program was doing when it wasn't executing my code. Suddenly it clicked and off I went. Same thing should happen with oop, eventually. CptKrf Yep and good luck. Stick to it, it will click and once it does should open another world to you. Like many types of programming at first you are going to write some pretty crappy code, and it is going to use a small subset of the features of OOP, but start there and then build. You won't be writing 100% elegant applications overnight, but you should see good results fairly quickly. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: when do vars go out of scope in this case?
JupiterHost.Net wrote: I just had a discussion about variables going out of scope (for memory considerations) The idea was presented that variables go out of scope as soon they're last referenced in a block, I always thought it was when the block ended. When a var goes out of scope and when the memory is available to perl again are two different things, and when the memory is available to perl again and when the memory is available on the system are two different things (at least on Unix systems). A variable can be reclaimed by the garbage collector as soon as there is no potential for it to be referenced elsewhere in the application. When the garbage collector will actually get to it is another question. And regardless, the memory will still be available to the same process, so it will not be available to other programs for instance until the program has ended. HTH, http://danconia.org I was just about to search for this and thought I'd ask to see if anyone knew offhand... In this example is it A or B? I'm thinking 'B' but never heard of 'A' before but I suppose it could be that way... { my $foo = load_100M_of_data(); print $foo; # $foo is using 100M of memeory ± # A) $foo is now out of scope (and therefore no longer 100M of memory) since its not used anywhere after that print() in this block # 100 lines of code without any use of $foo } # B) $foo is now out of scope (and therefore no longer using 100M of memory) I'm thinking its B and and the best way to reclaim the memory in this case is to undef()ine $foo when its no longer used in the block. Any insight would be very interesting no doubt :) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: when do vars go out of scope in this case?
Dr.Ruud wrote: Wiggins d'Anconia: the memory will still be available to the same process, so it will not be available to other programs for instance until the program has ended. And even that is not entirely true, because the memory manager of your OS can decide to swap stale stuff from precious RAM to disk, making the memory available for the same process or for other programs. Good point http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: A Strange Syntax
Adriano Ferreira wrote: On 12/5/05, Jennifer Garner [EMAIL PROTECTED] wrote: print ${*{$::{sym}}{HASH}}{name}; How to analyse the last sentence of that code?Thanks. From perldoc perlref 7. A reference can be created by using a special syntax, lovingly known as the *foo{THING} syntax. *foo{THING} returns a reference to the THING slot in *foo (which is the symbol table entry which holds everything known as foo). $scalarref = *foo{SCALAR}; $arrayref = *ARGV{ARRAY}; $hashref = *ENV{HASH}; $coderef = *handler{CODE}; $ioref = *STDIN{IO}; $globref = *foo{GLOB}; So $::{sym} returns the glob symbol sym on the main package ($main:: or $::), takes a reference to its HASH part, and returns what it got in the key name. Piece of cake, ain't it? Regards, Adriano. Now that you understand it, replace it with $sym-{name} so the next person doesn't have to ask. Unless you are using a really old Perl. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: File Test Question
Dave Adams wrote: *My Code:* my $logfile = logfile_with_content; if (-w $logfile) { print (True - file exists but empty); } if (-s $logfile) { print (True - file exist and has content); } *My Output:* True - file exists but empty True - file exist and has content *My Question:* Why do both test evaluate to true when the file called logfile_with_content is 5K in size? I would expect the second file test to only work? Any advice? -w tests whether the file is writable by the current effective UID/GID, it has nothing to do with the contents of the file. perldoc -f -e For more details. http://danconia.org Thanks -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: You've read the Llama, now what?
Randal L. Schwartz wrote: Tom == Tom Yarrish [EMAIL PROTECTED] writes: Tom So it makes it difficult for me to apply what I've read from the Tom O'Reilly books to real world problems (and I've read the Llama Tom book a few times). But have you also read the Alpaca? That's the natural next book after the llama. And as a non-author of said book I recommend it as a good next step. It filled a void long overdue in the Perl book space. (No affiliation with the authors or O'Reilly.) http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: help with matching
Rob.Savino wrote: I'm working on a simple script to get a list of users who do not exist while () { $user = system(echo $_); $result = system(dsquery user -samID $_); } if (!$result) { print $user\n; } Here is my problem, dsquery user -samID should return nothing if a user does not exist. I was hoping the script would print $user only if there was no $result from dsquery user -samID. However, not only does it print every $user regardless of the was not $result, it also prints every $result. Can someone tell me why this is? perldoc -q output of a command http://danconia.org Thanks, Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Which logger do I want? Or write my own? How?
Siegfried Heintze wrote: I have a couple of batch jobs that run every couple of hours. They scrape web sites and populate an MSAccess database. I would like to write a GUI to monitor them. Presently all my diagnostic print statements just scroll by and they are very hard to read. I would not want the batch processes to hang just because the GUI logger was not being run. Right, you should keep the two processes separated. I was thinking writing a GUI client that listens for UDP packets and displays the results using wxWindows -- maybe one tabbed pane per server process. Each tabbed pain would allow me to view the progress of each process. Yikes, sounds like over kill for such a simple task. What would be the best way to take all these diagnostic print statements that are spewing out lots of text and send it somewhere? (1) I did a search on CPAN and found there were several matches to Logging. They all looked very special purpose. Am I mistake or perhaps I need to search CPAN with a different keyword? Log::Log4perl is excellent and has an incredible array of functionality. (2) Regardless of whether CPAN has a module, I'm kinda curious: (2a) is there a way to serialize a hash table and send it thru a socket? (and of course, deserialize on the other end)? Sure there are a bunch, not the least of which is Storable. (2b) What about RPC -- I see from Advanced perl program there is such an implementation for perl. Would that be an effective logger? I don't think I want guaranteed delivery, however. I would like the option of not running the client. Again sounds like overkill to me. Why not just have the app log to a flat file. Then write whatever kinds of mechanisms you want to read, listen, parse that file however is appropriate. 'tail -f' might be all you would need. Start out small, then build on later. Leave the logging as part of the app, but do it simply; it shouldn't form the core of what you are doing. Leave log viewing and handling to a separate suite of apps, scripts, whatever. HTH, http://danconia.org Thanks, Siegfried -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Taking Multiple Values for The Same Form Field.
Bob O'Neill wrote: Use list context: my @names = $q-param('name'); Cheers, Ovid I've found this thread very helpful, and have changed it to use Vars (from http://users.easystreet.com/ovid/cgi_course/) as I need a hash. This has replaced the following: foreach $entry (param()) { $fieldhash{$entry}=param($entry); Checkentry(param($entry)); } with: my $q=new CGI; my %fieldhash=$q-Vars; which is much neater. My subroutine Checkentry untaints the input. Is there an easier way which will allow the hash values created by Vars to be passed to my subroutine without stepping through a foreach loop? If I understand correctly then you want a hash reference to pass the whole hash around at once. perldoc CGI Should help, CVars understands its context, so calling it in scalar context will result in it returning a hashref instead of a hash. my $params_ref = $q-Vars; http://danconia.org Bob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: hardcoded paths
Dermot Paikkos wrote: Hi, I am moving a site from once host to another. There are lots of hardcoded fully qualified paths to the localhost (EG http://myserver/cgi-bin/someprog.pl?name=val http://myserver/css/mystyle.css). I am pretty sure this isn't good practise but I am not a bit lost as to what are good alternatives. I don't want to make the same mistake and have to do all this editing again next time the hardware changes. Should I be trying to create a module with these paths in? Or is there some other way? Thanx. Dp. Relative URLs as David mentioned would be good whereever they can be used. The other option I use is to create a Setup.pm module that contains constants for these things. use constant CONFIG_URL_BASE = 'http://yoursite.com'; use constant CONFIG_URL_CGI_BASE = 'http://yoursite.com/cgi-bin'; Then you need to export those constants into the calling code. The only bummer about using constants is that they don't interpolate inside strings, but I have settled on using concatenation and prefer to have the extra overhead to have the ease of changing all URLs on a site at once. This also makes module code that generates links reusable across sites. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: CGI Upload() for nonexistent files?
Joby Jones wrote: Hello all, I have a question about the CGI upload() function. Why does it return a valid file handle to a file that does not exist on the client (web browser) machine, and what's the best way to handle this? Presumably because this is really a client side error. It is not an error to upload a zero length file, a file could need to be created but empty, and you could want to have a program do that. So it is not unreasonable to think that a file upload could be empty, which means CGI has to handle the case where a file is uploaded but empty. Chances are good the browser is creating the proper HTTP request despite the local file not existing, but to me that is a browser fault. CGI just sees the header that says there is a file coming, then no data so it creates the file, puts nothing in it, and happily crunches along. Details: 1. A user enters a nonexistent file name in an upload field in a form handled by my cgi script. (E.g. on windows c:\uplaodthis.txt -- note typo). 2. My cgi script does something like this: my $q = new CGI; if(defined($q-param('Upload'))){ my $upload_file_handle = $q-upload('upload_file'); if(defined($upload_file_handle)){ print Valid file handle to empty file is:\n . Dumper($upload_file); } } 3. It outputs: Valid file handle ... $VAR1 = bless( \*{FH::uplaodthis.txt ...}, 'Fh' ); What to do? --- Currently, I write out all valid file handles (checked for basic security problems as described in perlsec). If the file is zero length, I delete it and report an error. Which just isn't very satisfying. Why is it not satisfying? It is a requirement of yours that the file not be empty NOT the CGI world at large, so this is an error you should be handling. Sounds like you are doing a fine job. What am I missing? Is there a better way? Doubtful. You could write a web server module to handle the case at the front end of the request but the only thing that really saves is a little processing time, you still have a server side error to throw. All advice and documentation pointers (beyond 'CGI' :-) appreciated. I say move on and work on bigger problems. Faulty user input, is well the fault of the user. Let them deal with the consequences of having to resubmit the form, assuming your error message is clear. http://danconia.org Thanks, joby -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: problem using a module
jm wrote: i'm modifying a script to run on a sun box that i do not have privileges to install modules in the normal perl paths. subsequently i installed DBI.pm into a modules subdir under my home dir. below are the 2 relevant lines: use lib $ENV{HOME}/modules/DBI; our $mysql_dbh = DBI-connect(DBI:mysql:host=x.x.x.x, user, password, {RaiseError = 1}); this is the error msg i get: Can't modify subroutine entry in scalar assignment at ./ca-cisco line 64, near ); line 64 being the our $mysql_dbh... line (yes the host is a valid ip address). this does work on a linux box with DBI installed in the standard location, so what do i need to do to get this to work where DBI is recognized by the script but not in the normal location? That seems like a very odd error. One thing I do notice is that you are including DBI in the path to 'use lib'. This would have to mean that the DBI module lives in $ENV{HOME}/modules/DBI/DBI.pm. Is that the case? Or should your use lib line just be $ENV{HOME}/modules?? HTH, http://danconia.org -- since this is a gmail account, please verify the mailing list is included in the reply to addresses -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: problem using a module
jm wrote: On 10/28/05, Wiggins d'Anconia [EMAIL PROTECTED] wrote: That seems like a very odd error. One thing I do notice is that you are including DBI in the path to 'use lib'. This would have to mean that the DBI module lives in $ENV{HOME}/modules/DBI/DBI.pm. Is that the case? Or should your use lib line just be $ENV{HOME}/modules?? HTH, http://danconia.org you're right; upon further reading (i'm still researching) i discovered that discrepancy and removed the /DBI, now i get Can't locate loadable object for module DBI in @INC (@INC contains: /asi/home/ca/jm5379/modules /usr/perl5/5.00503/sun4-solaris /usr/perl5/5.00503 /usr/perl5/site_perl/5.005/sun4-solaris /usr/perl5/site_perl/5.005 .) at /asi/home/ca/jm5379/modules/DBI.pm line 254 which does show my dir prepended to @INC. looking just now in DBI.pm i see the following notes a little above line 254: # If you get an error here like Can't find loadable object ... # then you haven't installed the DBI correctly. Read the README # then install it again. so i guess just copying the file isn't going to cut it this time. oh well. thanks for the quick response. back to the drawing board. Yep. Your best bet is to use CPAN to install the module. One of its configuration parameters will allow you to specify a prefix of where to install modules, specifically 'makepl_arg'. Check the archives of this list or google for further information. How to install modules into a non-standard location is a widely covered topic. HTH, http://danconia.org -- since this is a gmail account, please verify the mailing list is included in the reply to addresses -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Is this script safe?
Ryan Frantz wrote: [snip] (my $new = $name) =~ tr/[a-z]/[A-Z]/; # trans the Alternatively, you could use the 'uc' function instead of 'tr'. perldoc -f uc At the very least remove the [], tr does not take a regular expression so the brackets above do not represent the character class as they would in a regex. So the above is replacing all '[' with '[' which is pointless. If you are going to use tr, instead of 'uc' for some reason, then, =~ tr/a-z/A-Z/; Is sufficient. perldoc perlop look for notes on transliteration. http://danconia.org [snip] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: how to avoid process die when can't create mysql dbh
Jeff Pan wrote: hi, Because of network problem,my script can't create Mysql dbh sometime when running,then it died.I have written code like this: my $mysql_dbh=DBI-connect(dbi:mysql:$mysql_db:$mysql_host,$mysql_user,$mysql_passwd, {PrintError = 1,RaiseError = 0}); I want to know how to adjust it,thanks a lot. According to the DBI docs connect should be returning undef on failure and should not be causing the script to die. Can you show us some code? In most cases you would catch an exception (death) caused by a module using eval to wrap the code in a block. perldoc -f eval eval { # code that could fail die ; } if ($@) { # handle error condition here, error is in $@ } HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: extract zip file
Tommy Nordgren wrote: Oct 25, 2005 kl. 6:21 AM skrev Pant, Hridyesh: Hi All, How to extract zip file using perl program... Thanks Hridyesh -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response system '/usr/bin/unzip',@OPTIONS,$zipfile; Time for me to rant about how the above is unacceptable for anything other than a one off script. Shelling out using 'system' or backticks is a last resort and should be used with care and the proper precautions taken. The above lacks proper error handling, security safe guards, and is inefficient and non-portable. So the ML archives for further discussion of how to properly shell out... http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: extract zip file
Tommy Nordgren wrote: Oct 26, 2005 kl. 7:56 PM skrev Wiggins d'Anconia: Tommy Nordgren wrote: Oct 25, 2005 kl. 6:21 AM skrev Pant, Hridyesh: Hi All, How to extract zip file using perl program... Thanks Hridyesh -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response system '/usr/bin/unzip',@OPTIONS,$zipfile; Time for me to rant about how the above is unacceptable for anything other than a one off script. Shelling out using 'system' or backticks is a last resort and should be used with care and the proper precautions Calling system with multiple paramaters don't 'shell out' as you call it.' It launches the tool in question directly, bypassing the shell entirely. The main security concern of calling accientally a trojan horse earlier in the users path, don't apply when using the array form of system, with an absolute search path Ok, fork/exec'ing, technically you are correct, the shell doesn't get a chance to re-interpret the command line. You are also correct that you avoid a trojan horse when someone places something earlier in the path, of course there is nothing to say that /usr/bin/unzip isn't a trojan horse itself, assuming it exists at all. Regardless the above code still doesn't catch a missing executable, no permissions to run said executable, or errors thrown by that executable, or on the flip side that it was actually successful. Though I haven't benchmarked it, for common practices shelling out is generally also slower than its native Perl bretheren, and of course portability falls all to pieces. So for proper applications something like Archive::Zip would be significantly better from interface, security, portability, and efficiency standpoints. http://danconia.org taken. The above lacks proper error handling, security safe guards, and is inefficient and non-portable. So the ML archives for further discussion of how to properly shell out... http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response - This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: HUP vs signal 9
Christopher Spears wrote: What is the difference between kill 1, SIGNAL and kill 9, SIGNAL ? By reading books and talking to people, I figured out that kill 1 is the HUP (hang up signal) and kill 9 is the kill signal. Don't they do the same thing (i.e. terminate a program)? I was told that kill 1 is a nicer way to end a program than kill 9. HUP is a catchable signal. Meaning the program receives notification that a signal has occurred and which signal. This allows the program to then act in a certain appropriate manner. For example, HUP is often used to restart a server application such as Apache. Generally the server will clear its configuration, re-read its configuration, and then re-perform any startup like stuffs. The KILL (9) signal is not catchable and causes an immediate death without proper cleanup. It is usually reserved for a runaway process that can't be killed with one of the other catchable kill signals like TERM or QUIT. perldoc perlipc For more about signals and their handling in Perl. man -s 7 signal For more about Unix/POSIX signals. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Finding all the files in a PC
Andrew McHorney wrote: Hello I am planning on developing a perl script that will find all the duplicate files (name, size and content) on a pc and remove the duplicate files. I have written a few scripts on a unix platform but non yet for a pc in a windows environment. Can someone provide a basic stub that will find all the files, the creation date and size and put them in a array. I want to avoid putting the directories in the array. This is because of various problems with a hard drive and putting files on various removeable media disks. Thanks, Andrew perldoc File::Find http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Project planning
Steve Bertrand wrote: Hi everyone, This question may seem odd, but here goes anyway. I've been working at an ISP for a few years now, and have been adding to/modifying their current accounting system since I've got here. Of course it is all Perl based. This isn't a technical problem I'm having, but the system has well over 100,000 lines of code in several files. I want to change course, and take a more organized approach to this. My question is if there are any good books (particular to Perl), on how to organize a large project like this to make it easier to consolodate code, find code, and otherwise prevent myself from continuously re-inventing the wheel. I am quite familiar with Packages, but I just need some guidance with documenting/planning of the project. Any tips very much welcome. Tks, Steve I am sure there are plenty of others, 3 I would suggest, - Learning Perl Objects, References, and Modules - Object Oriented Perl - The Pragmatic Programmer Sounds like the system has grown enough that it should be broken into objects to prevent duplication, among all of the other things OOP provides. The first two above should give you the tools to accomplish the suggestions about general programming that the third provides. Good luck, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Need Some Guidance
Gladstone Daniel - dglads wrote: I noticed that there is various version of Learning Perl + Perl Cookbook The most version (Version 4) costs the most. Does it matter the version if I want to learn or do I need to get the most recent version? What is the groups thoughts? Daniel Gladstone ([EMAIL PROTECTED]) Please start a new thread with a new subject. It definitely matters for the Learning series. The newer versions are much improved over previous ones. For the cookbook chances are it matters less, though you will want to pay attention to errata. And obviously the newer the version the more and probably better recipes it will contain. As far as buying two books, I would get both in the Learning series before picking up the cookbook. Some will definitely disagree about that last part, but I think it depends on how much you already know and what your plans are. The cookbook provides excellent *snippets*, but you can find snippets galore on the web, the 2nd in the learning series will help you build a much stronger foundation that should allow you to come up with more workable programs. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Config File Layout
Ryan Frantz wrote: Perlers, I'm working on a script that will need to email clients if it finds files in their respective outbound directories. I've decided on a simple config file: [foo] [EMAIL PROTECTED] [bar] [EMAIL PROTECTED] [EMAIL PROTECTED] I've written a simple parser but it doesn't check for incorrect syntax. I looked at some of the Config:: modules and they appear to require Name=Value pairs. So my question is one of design; should I use the name=value pairing and one of the Config:: modules, or just leave it as is? I'm going to be the only one maintaining the config file but, of course, I want the script and config file to be maintainable even if I'm not around. One of the Config:: modules should handle your format above. You might also consider AppConfig, http://search.cpan.org/~abw/AppConfig-1.56/lib/AppConfig.pm HTH, http://danconia.org ry -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $CGI::DISABLE_UPLOADS
Bill Stephenson wrote: I've been testing the $CGI::DISABLE_UPLOADS and $CGI::POST_MAX variables and I don't think I've got it feature working as it should. The docs say this: CGI.pm also has some simple built-in protections against denial of service attacks, but you must activate them before you can use them. snip $CGI::POST_MAX If set to a non-negative integer, this variable puts a ceiling on the size of POSTings, in bytes. If CGI.pm detects a POST that is greater than the ceiling, it will immediately exit with an error message. It seems to me that my script will not exit until uploading the entire POST has been completed. So, here are my questions about this: Right, but the script exits immediately. I *suspect* the complete request must be sent to the web server regardless of whether the script is going to fail. Exiting immediately just means that CGI will not allow execution of anything beyond its initial preparations, rather than meaning it will truncate the request. At least that would be my interpretation... But I didn't have a look at the modules source, you might want to check there for confirmation. http://danconia.org Do I misunderstand the above? (ie. the script should upload the entire POST before exiting with an error) Is there something wrong with my test script (I suspect this must be the case, please see it below) Or... is there something wrong with CGI.pm? (this seems to be a longshot) I'd really appreciate any help you all can give me with this. Kindest Regards, -- Bill Stephenson code #!/usr/bin/perl # deny_upload.cgi use CGI; use File::Basename; use strict; $CGI::POST_MAX=1024 * 5; # max 100K posts $CGI::DISABLE_UPLOADS = 1; # no uploads my $Q = new CGI; my $message; # trap error with this... if (!$Q-param('file') $Q-cgi_error()) { $message = $Q-cgi_error(); error_trap( $message); } # or this... # if ($Q-cgi_error()) { # $message = $Q-cgi_error(); # error_trap( $message); # } if (!$Q-param) { print $Q-header; print qq ~!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN http://www.w3.org/TR/html4/loose.dtd; html head titleUpload Test/title /head body form id=upload_logo_form method=post action=/cgi-bin/test/deny_upload.cgi enctype=multipart/form-data input type=file name=file size=30 ptextarea name=text rows=4 cols=40put too much text in here/textarea/p input type=submit name=upload value=Upload Stuff /form /body /html~; exit 0; } # get on to uploading the file... if ($Q-param('file')) { my $data; my $filePath; my $file = $Q-param('file'); fileparse_set_fstype(MSDOS); $file = basename($file); $filePath = /test/$file; open (SAVE,$filePath) or error_trap($message= Error:: $! :: Can Not Upload $file: \n); while (read($Q-param('file'),$data,1024)) {print SAVE $data;} close SAVE; print $Q-header; print $Q-start_html(-title = Uploaded it anyway); print Uploaded it anyway; print $Q-end_html; exit 0; } if ($Q-param('test')) { print $Q-header; print $Q-start_html(-title = Lotsa Text); print $Q-param('test'); print $Q-end_html; exit 0; } sub error_trap { print $Q-header; print $Q-start_html(-title = MyApp Error Screen); print $message; print $Q-end_html; exit 0; } /code -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Sending HTML file as mail from mail command (mail -s )
Josh Brown wrote: Mazhar wrote: Hi Folks, i have a requirement where in i need to send alerts to a set of users for which i have developed a script and it is working fine. For the body of the mail i am writing into a text file everytime and i am sending across using the command, cat textfilename | mail -s Subject set of users This above is working fine i need help for sending the same textfile as a HTML file as the body of the mail please help me. Thanx in Advance Regards Mazhar Hi Mazhar, What I do is open a filehandle to the sendmail application, then I print in the headers I want. You can be very flexible with it and there really is no guess work. There is lots of guess work. What if the path is different, are you going to code in every possible system location, or just hope the path is correct and open a security hole. What about necessary switches to sendmail? What if sendmail isn't even installed? What if no command line mail handler is installed? What if you want to send both text and html, then you need to setup boundaries and a proper preamble. Avoid the headaches, stick with a module that will handle all of that for you. Dealing with mail messages by hand is or will quickly become a nightmare. http://danconia.org Here is a quick example. open (MAIL, |/usr/sbin/sendmail $recipient) or die Could not open sendmail; print MAIL To: $recipient\n; print MAIL From: $sender\n; print MAIL Subject: $subject\n; print MAIL Content-Type: text/html\n\n; print MAIL $html\n; print MAIL \n.; close MAIL; That should work just fine, it is only for one recipient but I think you just have to make sure they are seperated by spaces. Hope that helps, -JB -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Formatting Variables
Ryan Frantz wrote: Perlers, Is there are way to format a variable before placing it into an array or hash? I have several variables that contain floating point numbers that I format prior to printing out: my $float = 12.3456; print %2.1f\n, $float; perldoc -f sprintf http://danconia.org I'd like to place these scalars into an array for later use/output in an HTML table and I figured I have to format them before they are entered in the array. Is this possible? Or is there a different/better solution? ry -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: TEST
Peter Scott wrote: On Thu, 06 Oct 2005 05:42:59 -0400, Tom Allison wrote: So make tests that just run the scripts and then examine the outputs. If there are unwanted side effects you can't undo from the test then you need to modify the script in some way. Is this where 'do' comes into use? No, I'd use 'system'. Otherwise the script will be affecting the calling environment in ways I'm not supposed to have to find out about with black box testing. This is why writing the tests *before* writing the code makes life so much easier. Still, that's hindsight. um... I have one problem with that. I often don't know what the script is supposed to actually do until I'm already writing it. Most of these are variations on a theme of log analysis or data mining. At least one well known person has said the same thing... but he appears to be in a minority. Personally, unless you're doing the programming equivalent of doodling, I can't see how you can write something before knowing what it does. Even if you only formulate the idea a moment before writing the code, the idea still precedes the code. This IMHO is a key to the whole test first. Write all of the tests you can ahead of time, that doesn't mean every tiny single unit test that you will ever have has to exist up front. Maybe it is just a unit to test whether your script exits true or not. The key here for me is that it gets me into the mindset and guarantees I have a testing harness that more tests can be added to, once I know what they should be. Yes, if you're doing a lot of iterative development, you may change the public interface that testing uses and have to rewrite the tests. That's the biggest problem I have with test-first. But I find it well worth it, because if I were to wait until the code was stable, I'd never have any tests. Test-first encourages me to think about my public interfaces in a good way. Right. It takes more time to write the individual code upfront, but it should save time in aggregate because if you have accurate tests then making additions/changes in the future will be faster (read: safer). Now if I could just find someplace that actually does this http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Query on sendmail problem
Dale wrote: Hi, I'm hoping someone can help me with an issue I've got with, I assume, sendmail. I've copied part of a script below. If I use the first To: line (which takes the e-mail address from a file - and this works) then a mail doesn't arrive. If, however, I used the second To: line (which is currently commented out - the xx is to stop spammers picking the address up from this mail) then a mail is received. I added a page after the sendmail just to make sure it was reading the e-mail address from the file (which it was) but it still doesn't seem to send. $manageremail is the correct variable name. In the datafile, I've had the e-mail addresses formatted properly (e.g. [EMAIL PROTECTED]) but also tried with \'s at appropriate places (e.g. [EMAIL PROTECTED]). I just can't get anything to work. Anyone have any ideas what I could be doing wrong. You're not using a module... Don't think that is what you meant though. Thanks in advance! - - open(MAIL, |/usr/local/bin/sendmail -t); print MAIL To: $manageremail\n; Are you chomp'ing $manageremail? If it has a newline on it in the file and you have added an additional new line above then you have stopped the header, surprisingly it should still be sending but below should be in the body. You should probably have a look at the mail logs generated by sendmail to see if it is complaining, and more specifically about what. http://danconia.org # print MAIL To: [EMAIL PROTECTED]; print MAIL From: [EMAIL PROTECTED]; print MAIL Subject: Escalation logged\n; print MAIL Hi $manager\.\n\n; print MAIL The following escalation has been logged from your team.\n\n; print MAIL Agent's Manager : $manager\n; print MAIL Agent's Name : $agentname\n; print MAIL Date Logged : $day\-$month\-$year\n; print MAIL Escalation Reason : $reason\n; print MAIL Short Description : $short\n; print MAIL Long Description : $long\n; print MAIL Justified?: $justified\n; print MAIL Name of Logger: $logger\n; close (MAIL); - - -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: question about # of files in a directory
ZHAO, BING wrote: Hi, first, I want to thank all who viewed my first question days before, especially to those who took time to answer it. It was trenmendous encouragement for a beginner perlee like me. Thanks again. My question: Is there a way to call or maybe get the # of files in a directory? I am trying to build a storage directory for files which automatically empits itself when the # files reaches 50. If there is some commands which do that(like whatever COMMAND(directory) ), the problem would be solved, I then will be OK to program the rest of perl. To be more specific, I have a CGI online page which takes uploaded files(press 'upload' on my website, then upload whatever text files, uaually DNA sequence files) then I need to modify the files a bit then save the files to the STORAGE directory, the directory can't be infinitely increasing, so I need to empty it when the time comes. And I need to keep track of the # of files in that 'damn' directory. Maybe you got better idea about how to store the files to the directory? Let me know then. perldoc -f opendir perldoc -f readdir perldoc -f closedir perldoc -f unlink This should get you started. You can also look into file globs though I have never preferred them, for whatever reason. perldoc -f stat perldoc -f sort Might also come in handy as presumably you want to remove the oldest, highest number, etc. -- UNTESTED -- opendir my $DIRHANDLE, '/path/to/dir' or die Can't get directory handle: $!; my @filelist = grep { $_ ne '.' and $_ ne '..' } readdir $DIRHANDLE; closedir $DIRHANDLE; if (@filelist 50) { for my $index (50 .. @filelist) { unlink $filelist[$index] or die Can't remove file $filelist[$index]: $!; } } Thank you all for reading my 'junk'. HTH, http://danconia.org best, Bing -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: PERL's equivalent to an include file
Please bottom post... Shelly Brown wrote: I would like to display the daily calendar information from a perl script: http://webapps.sbuniv.edu/daycal/ within an html page so it looks like this: http://www.sbuniv.edu/. Right now I have to manually enter the calendar information. I would like for it to be dynamic. Make sense? Most likely your web server software has the ability to parse pages, aka server parsed pages, and you can probably make an include call exec on a program on the local filesystem. The program should output on STDOUT the HTML code for the calendar. Depending on which webserver you run you may also be able to handle this directly with ASP or the like, but then that wouldn't be Perl. Going the embedded Perl route is probably more difficult and not the direction to head... http://danconia.org On 9/27/05, Shelly Brown [EMAIL PROTECTED] wrote: I would like to include a PERL file within an html or asp file. How do I do that? I'm working on a Windows server. -- Shelly Brown -- Shelly Brown -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Shift Question
Mulander wrote: If I understood you question properly you want to know why people use shift in subrutines and how does shift work. I will try to make it short: shift works on lists, it removes the first element of the list ( the 0 indexed element ) and returns it as a lvalue ( if there are no more elements in a list it returns undef ). Here is an example: my @list = qw(a b c d); print shift @list,\n; print my list is now @list\n; print shift @list,\n; print my list is now @list\n; print shift @list,\n; print my list is now @list\n; print shift @list,\n, print my list is now @list\n; this should print something like this ( althoug I did not have the time to test it ) a my list is now b c d b my list is now c d c and so on... If you use shift without giving it the list name to work on it will refer to @_ or @ARGV ( it is decided upon the file scope ). So when you define a sub like this: sub somesub { my $arg1 = shift; } You did something simmilar to my $arg1 = $_[0]; but more elegant ( in my opinion ) and you removed the first element from the arguments list ( witch is quite usefull ). Hope this will clear some things up, you can check also: perldoc -f shift perldoc -f unshift perldoc -f pop perldoc -f push Additionally a very common idiom and where you may be seeing this so much is within OOP style programs/modules. In the case of object oriented syntax Perl automagically tacks on the class name or instance object as the first argument to the subroutine (method). So you will very commonly see, sub class_method { my $class = shift; my (%other_args) = @_; } or sub instance_method { my $self = shift; my (@other_args) = @_; } These would be called like, Class::Object-class_method(key1 = 'val1'); or my $object = new Class::Object; $object-instance_method('arg1','arg2'); I often use this syntax for writing non-OOP libraries just because it has become so common otherwise. In which case having the name of the class really doesn't matter much. Finally, it is common to use 'shift' with subroutines that take a very common x # of arguments, and then take a hash like list. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: general retry function
Ing. Branislav Gerzo wrote: Hi Perlers, I have one nice question for you, I was run into common problem: need to repeat certain number of times something, until is succesful. For example - download webpage, FTP upload, connect to some host and so on. I ask you for some general (or it can't be possible - FTP upload) function, for example I will call: ftpupload($cfg, 10); will call ftpupload() with $cfg ($cfg-{user}, $cfg-{pass},...) and 10 is number of retries. Could be anyone so nice and write it ? I have some snippets here, using eval {} and catch errors with calling recursive sub, but I don't think thats the best option. Thanks in advance. /brano You haven't shown us what you have tried, or where it failed, only suggested something about eval and recursive subs, which neither of which should be pertinent here. Show us your attempts... In any case... I would write this such that the number of retries is part of your configuration, assuming you really do want the ftpupload sub to handle keeping track of that, for now I will assume you do. In pseudo code this might looking something like... use Net::FTP; my $cfg = { 'user' = 'username', 'pass' = 'password', 'host' = 'host.com', 'retries' = 10, 'filename' = '/path/to/file', 'dir' = '/remote_dir', }; ftp_upload($cfg); sub ftp_upload { my ($config) = @_; # error handling on argument list $config-{'retries'} ||= 3; my $try = 0; while ($try $config-{'retries'}) { # connect # change directory # upload file # disconnect if (success) { return; } } return Failed after $config-{'retries'} attempt(s); } I assume you can read the docs for Net::FTP to handle the actual FTP code, they are fairly complete and straight forward. It is also a core module, and the *best* way to handle FTP transfers. Good luck, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: how to use perl modules
Abhishek Dave wrote: hello all, i've wrote a small test subroutine in my file name test.pm and in the same directory i worte a perl file in which i've to call this subroutine in this perl program Capitals, punctuation, and full words are a good idea when posting to a public forum. Poor grammar from non-native speakers is certainly tolerated, but if you can write what you wrote above then you know enough to punctuate and capitalize. And very few language - English dictionaries would produce such output. I dont know how to use perl modules pls let me knwo abt that as it will solve my lots of problems test.pm sub ReturnValue() { my $a=10; return ($a); } call.pl use test; print ReturnValue(); --I don't know abt the moduls in perl Did you run the program? What did it say and what does that tell you? Pls help me in this regard asap What have you researched, what have you read on the topic? Have you searched google on How to write Perl modules? perldoc perlmod perldoc perlmodlib perldoc perlmodstyle waiting for reply from perl group http://danconia.org Thanks Beginner -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Camel book relevance
Gonzillaaa wrote: Hello, another beginner looking for a book... Only this time I'm pretty much decided by the Camel book I just wanted to know how relevant you guys think is it for Perl today... What I mean is how much the language has evolved since the book was last published and if that change has render it irrelevant in some areas. Thanks. For beginners I would suggest getting Learning Perl rather than the Camel. The Camel is written as a reference, a very thorough one at that. The Learning series is written to teach and includes exercises, etc. It is known as the Llama. Unless you are already very, very familar with language constructs and are a very good developer, then the camel will probably not serve you as well. I have reviews of many of the Perl books on my site: http://danconia.org/cgi-bin/request?handler=Content;content=StaticPage;label=perl And information about most can also be found at: http://learn.perl.org Just a couple of cents, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Camel book relevance
Please bottom post... Gomez, Juan wrote: Hi ! I am a beginner too and can tell you this I use PERL a lot, I work with a lot of data and PERL helps me to manage all the data, I have started doing some CGI programming with it and it is great now all the text mode information I can put it in a web page for me it has work i think it would work for you Perl or perl, but never PERL. The first is the general name for the language. The second is usually used in reference to the interpreter. http://danconia.org cheers -Original Message- From: news on behalf of Gonzillaaa Sent: Sun 9/25/2005 1:50 AM To: beginners@perl.org Subject: Camel book relevance Hello, another beginner looking for a book... Only this time I'm pretty much decided by the Camel book I just wanted to know how relevant you guys think is it for Perl today... What I mean is how much the language has evolved since the book was last published and if that change has render it irrelevant in some areas. Thanks. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: html file with form and onSubmit=return check_form(this)
Edgardo Lust wrote: Hi. I have a html file (created with Dreamweaver) with one form and submit button with form method=POST action=/cgi-bin/contact.pl onSubmit=return check_form(this) input type=hidden name=success value=/contacto/message.htm input type=hidden name=required-to value=[EMAIL PROTECTED] input type=hidden name=subject value=-- NEW CONTACT -- I need my perl script to return a valid value then the user can see message.htm page How can I do? Thanks Edgardo What do you mean by return a valid value? You can either redirect to message.htm or read it in and return the contents. As a side note the above is basically an open relay, depending on your other form fields a specially crafted message can probably be used to send an e-mail to anyone. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: tsv
Matthew Sacks wrote: Hello Folks, Has anybody used Data::Table? I am specifically interested munching some huge tab separated file. When reading/writing it, I want to be very strict about what characters comprise valid data. Suggestions? -matthew Text::CVS_XS is also popular for this type of thing. Despite the name it will handle data formatted by definitions other than commas. If you are going to be manipulating the data via similar methods as an SQL database you may wish to consider DBI using the DBD::CSV driver. Having said that I don't have specific experience or reasons not to use Data::Table. Good luck, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Reverse If and Normal Else
Frank Geueke, III wrote: Hi everyone. Okay, so maybe this one is a silly question. I have a fairly large script and I have a bunch of places where I'm following a reverse if with a normal else and perl keeps complaining about it. It seems to make sense to me, but I guess its bad syntax. Here is one of them: display_nothing() if ($match_type eq 'none'); else { } Now I like the reverse if because it takes up one line instead of four (I like braces on their own lines - see else). But this error... Not really because the ; is a statement terminator. If it is really about the number of lines there is nothing preventing you from just putting it all on one line. if ($match_type eq 'none') { display_nothing(); } else { } Personally I would rather see it just written out, a couple lines make little difference if the rest of your code is structured well. I suppose you could also reverse the logic and then your display_nothing would get shoved to the bottom of the whole block which is typically what I would do, so, if ($match_type ne 'none') { } else { display_nothing(); } Or, unless ($match_type eq 'none') { } else { display_nothing(); } HTH, http://danconia.org syntax error at /usr2/login/fjg/hotspot_tracker/search_by_ip_or_mac.cgi line 70, near else ...keeps coming up. Is there a way to keep the reverse if and use an else (or something like it) that anyone knows of? Thanks. ~Frank -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: trying to run net::ssh::perl have errors
Please bottom post... Please group reply so others can help and be helped... O'Brien, Bill wrote: Thanks I think that work but know it appears I lost /bin/sh, error below any ideas? [EMAIL PROTECTED]:~/.cpan/sources/modules/Crypt-RSA-1.56$ which sh sh: Command not found. [EMAIL PROTECTED]:~/.cpan/sources/modules/Crypt-RSA-1.56$ make make: /bin/sh: Command not found make: *** [blib/lib/Crypt/.exists] Error 127 [EMAIL PROTECTED]:~/.cpan/sources/modules/Crypt-RSA-1.56$ which make /bin/make [EMAIL PROTECTED]:~/.cpan/sources/modules/Crypt-RSA-1.56$ /bin/make make: /bin/sh: Command not found make: *** [blib/lib/Crypt/.exists] Error 127 Yikes, sounds like a very messed up Cygwin install, or something is clearing your path. Try displaying the PATH env variable, under bash use: echo $PATH And see if it has been cleared. If it looks normal then I would reinstall Cygwin from scratch. This is about the extent of my knowledge and experience with Cygwin installation. If that doesn't fix it then you might try posting to a Cygwin list to get installation assistance. The key for Perl here is that the modules you are trying to install have a C component that must be compiled, hence the need for gcc, but that is about the extent of the issue from a Perl perspective. HTH, http://danconia.org Thanks Bill -Original Message- From: Wiggins d'Anconia [mailto:[EMAIL PROTECTED] Sent: Wednesday, September 21, 2005 5:32 PM To: O'Brien, Bill Cc: beginners@perl.org Subject: Re: trying to run net::ssh::perl have errors O'Brien, Bill wrote: Greetings, Not sure if this is correct place, but I need to start somewhere, I have cygwin install on my work station and I'm trying to to use NET::SSH::Perl but I'm getting an error. I have installed NET:SSH:Perl-1.28, but I'm getting the following error, when I run the script. Can't locate Math/GMP.pm in @INC (@INC contains: /usr/lib/perl5/5.8.5/cygwin-thread-multi-64int /usr/lib/perl5/5.8.5 /usr/lib/perl5/site_perl/5.8.5/cygwin-thread-multi-64int /usr/lib/perl5/site_perl/5.8.5 /usr/lib/perl5/site_perl /usr/lib/perl5/vendor_perl/5.8.5/cygwin-thread-multi-64int /usr/lib/perl5/vendor_perl/5.8.5 /usr/lib/perl5/vendor_perl .) at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/Util/SSH1MP.pm line 7, GEN0 line 1. BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/Util/SSH1MP.pm line 7, GEN0 line 1. Compilation failed in require at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/Util.pm line 56, GEN0 line 1. BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/Key/RSA1.pm line 6, GEN0 line 1. Compilation failed in require at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/SSH1.pm line 13, GEN0 line 1. BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/SSH1.pm line 13, GEN0 line 1. Compilation failed in require at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl.pm line 52, GEN0 line 1. I'm trying to install the GMP version MATH::GMP 2.04 but that is failing with these errors but I'm not sure why it is failing: [EMAIL PROTECTED]:~/.cpan/sources/modules/Math-GMP-2.04$ make test gcc -c -DPERL_USE_SAFE_PUTENV -fno-strict-aliasing -pipe -I/usr/local/include -DUSEIMPORTLIB -O2 -DVERSION=\2.04\ -DXS_VERSION=\2.04\ -I/usr/lib/perl5/5.8.5/cygwin-thread-multi-64int/CORE GMP.c gcc: not found make: *** [GMP.o] Error 127 gcc not found indicates you don't have the gcc compiler installed. Try installing gcc through Cygwin, then re-try the Math::GMP installation. http://danconia.org Thanks Bill -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: RE : Is it possible to force a particular order in a hash?
Jose Nyimi wrote: -Message d'origine- De : John W. Krahn [mailto:[EMAIL PROTECTED] Envoyé : jeudi 22 septembre 2005 23:26 À : Perl Beginners Objet : Re: Is it possible to force a particular order in a hash? Dave Adams wrote: I have a hash that I need to use later and display some values in a particular order. Perl comes up with its own way of ordering it but I am wondering if I can instruct perl to have it listed in the way that I want. You could store the ordered keys in a separate array or you could use the Tie::IxHash module. I'm wondering if Tie::IxHash is suitable here. Indeed, from the module doc i'm reading the following: This Perl module implements Perl hashes that preserve the order in which the hash elements were added. It seems that the OP here wants to customize the order, not only preserve the order in which elements were added during hash contruction. From the perldoc: Reorder This method can be used to manipulate the internal order of the IxHash elements by supplying a list of keys in the desired order. Note however, that any IxHash elements whose keys are not in the list will be removed from the IxHash. Based on that and the push,pop,shift,unshift,splice and replace methods you should be able to simulate just about any reordering operation. http://danconia.org Input order: AUTHOR LANGUAGE TITLE Desired output order: TITLE AUTHOR LANGUAGE Suggestion from Waldemar Jankowski looks promizing ... Regards, José. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: trying to run net::ssh::perl have errors
O'Brien, Bill wrote: Greetings, Not sure if this is correct place, but I need to start somewhere, I have cygwin install on my work station and I'm trying to to use NET::SSH::Perl but I'm getting an error. I have installed NET:SSH:Perl-1.28, but I'm getting the following error, when I run the script. Can't locate Math/GMP.pm in @INC (@INC contains: /usr/lib/perl5/5.8.5/cygwin-thread-multi-64int /usr/lib/perl5/5.8.5 /usr/lib/perl5/site_perl/5.8.5/cygwin-thread-multi-64int /usr/lib/perl5/site_perl/5.8.5 /usr/lib/perl5/site_perl /usr/lib/perl5/vendor_perl/5.8.5/cygwin-thread-multi-64int /usr/lib/perl5/vendor_perl/5.8.5 /usr/lib/perl5/vendor_perl .) at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/Util/SSH1MP.pm line 7, GEN0 line 1. BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/Util/SSH1MP.pm line 7, GEN0 line 1. Compilation failed in require at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/Util.pm line 56, GEN0 line 1. BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/Key/RSA1.pm line 6, GEN0 line 1. Compilation failed in require at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/SSH1.pm line 13, GEN0 line 1. BEGIN failed--compilation aborted at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl/SSH1.pm line 13, GEN0 line 1. Compilation failed in require at /usr/lib/perl5/site_perl/5.8.5/Net/SSH/Perl.pm line 52, GEN0 line 1. I'm trying to install the GMP version MATH::GMP 2.04 but that is failing with these errors but I'm not sure why it is failing: [EMAIL PROTECTED]:~/.cpan/sources/modules/Math-GMP-2.04$ make test gcc -c -DPERL_USE_SAFE_PUTENV -fno-strict-aliasing -pipe -I/usr/local/include -DUSEIMPORTLIB -O2 -DVERSION=\2.04\ -DXS_VERSION=\2.04\ -I/usr/lib/perl5/5.8.5/cygwin-thread-multi-64int/CORE GMP.c gcc: not found make: *** [GMP.o] Error 127 gcc not found indicates you don't have the gcc compiler installed. Try installing gcc through Cygwin, then re-try the Math::GMP installation. http://danconia.org Thanks Bill -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: perl script for a trace file
oracle s wrote: Hello, I have a trace file( network simulator trace file) and I need to write a perl script which computes drop probability and delay. The parameters are read from the trace file and I need to do all these calculations in the perl script. Since I have no knowledge of perl, could you please advise me as to how i need go about writing this script ( the logic of the script and the flow). Thank you, Anu This is not generally a free script writing service. Most would start either: http://learn.perl.org or http://jobs.perl.org Or offline with the Llama, aka Learning Perl from ORA. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Forcing a save as' dialogue box to come up on left click
Tony Frasketi wrote: Wiggins d'Anconia wrote: Most browsers will provide this functionality if the return header is application/octet-stream rather than text/html or the like. In the case of IE you may have to fool the browser into thinking it is getting something different than it is based on the URL, because it likes to look there for a file extension to determine the file type too. HTH, http://danconia.org Hi Wiggins Thanks... I just tried putting these three lines in a .htaccess file in a particular directory... AddType application/octet-stream .cgi AddType application/octet-stream .txt AddType application/octet-stream .htm Alternatively, I also triedAddType application/octet-stream .cgi .txt .htm Interesting way to do it, not what I intended. Have you 100% confirmed that the header is being passed back correctly? I am not sure how Apache (or whatever web server you are using) handles setting the type, it might be finding it from somewhere else that is overriding it. There is a module for Firefox/Mozilla called Live HTTP Headers that will help you confirm what is being sent. What I was intending was to call the cgi script and rather than it printing the normal text/html header it would print the header directly, that way you are guaranteed to be operating the way you intended. Using the Mozilla 5.0 Suite browser, I get the following results And then trried clicked on links to a .cgi file, a .txt file, and a .htm file in that directory Only the .htm file automaticaly brought up a 'Save as...' diaglogue box as I left clicked on the link to the .htm file when I clicked on the link to the .txt file, the contents of the .txt file appeared in a Wordpad window. This is windows picking up the association based on the extension (probably), didn't you know it was smarter than you? ;-) When I clicked on the link to the .cgi file, the .cgi file was executed and the results displayed in the browser window. One out of three right! Using the Microsoft IE 6.0 browser, I get the following results .htm file - Displays the .htm file in browser window .txt file - Displays the .txt file in browser window .cgi file - Executes the .cgi script and displays results in browser window zero out of three right! Yeh I suspect that is IE picking up on the URL extension. Using Firefox 1.0 browser, I get the following results... .htm file - brings up the 'Save as...' dialogue box .txt file - brings up the 'Save as...' dialogue box .cgi file - Executes the .cgi script and displays results in browser window The .cgi problem is probably because you have a handler setup for .cgi files that trumps the AddType call. What is the header printed by the .cgi file? It should be able to print its own header of application/octet-stream followed by the contents of a file and it should work correctly. SO... Filefox wins by getting two out of the three right! This method doesn't look very hopeful at this point! I know I have used this method before, and I have done so recently from within the context of a different web framework (specifically Interchange). As to your question about Content-Disposition it can be used to preset the filename that the user sees in the Save as... dialogue, but is again not standard, it is just convention and will depend on the browser supporting it, to my knowledge the major browsers[1] do support it. Thanks again Tony Frasketi Keep at it, I suspect you will get it to work... http://danconia.org [1] When I say major browsers I mean Mozilla (and variants, Firefox, etc.), IE (some recent version, probably newer than 4.x), Safari. I know there are others but I don't have a copy so can't say specifically how they act, they may work as well. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Forcing a save as' dialogue box to come up on left click
Tony Frasketi wrote: What I was intending was to call the cgi script and rather than it printing the normal text/html header it would print the header directly, that way you are guaranteed to be operating the way you intended. Hi Wiggins Thanks for this suggestion... I've tried the following bit of CGI script with three different file types (.txt, .cgi, .dat) and in each case *DO* get the 'Save as...' dialogue box to come up and when I select 'Save to disk' and click ok, It appears as if a transfer occurs but only a zero-length file is saved to my local hard disk directory. The code is as follows... Ok, so almost there let's back up a step and understand the whole thing. The HTTProtocol is very similar to other common net protocols where there is a header section and a data (or payload) section. The two are separated by a blank line. So right now you are providing the header (apparently correctly). The client reads that information and based on what it knows how to handle it decides on a way to use the payload. In this case we are giving the browser less than optimal descriptors of the payload. Basically we are telling it that there is something coming and that neither I nor you know what it is. So it does the only thing it can, Save as The only hint you are providing it a suggestion about what to call that thing. So right now you are providing a header, but not a payload, let's add it #!/usr/local/bin/perl -w # testoctetstream_1.cgi # My base directory and base directory URL my($basedir) = base directory; my($baseurl) = base URL; # Location of the file to be downloaded $fileloc = $basedir/cgi-bin/test/xxx.txt; #$fileloc = $basedir/cgi-bin/test/testdu1.cgi; #$fileloc = $baseurl/cgi-bin/test/testdu.dat; # Name of file to be downloaded $filename = xxx.txt; #$filename = testdu1.cgi; #$filename = testdu.dat; # NOTE: Uncomment the desired $filename and $fileloc above # Set The headers print Content-Type: application/octet-stream;\n; print Content-Disposition: attachment; filename=\$filename\\n; # --- # Note: Can't figure out what to put in here to actually download # the darn file!!! # --- This is the simple part, and probably looks a little like. open file... read in file... print file back to browser... close file There are simpler ways to do this, but what I have come to use looks like: my $READHANDLE; unless (open $READHANDLE, $file) { # error handling... } binmode $READHANDLE; $| = 1; while ( my $length = sysread $READHANDLE, my $buffer, $block_size ) { next unless defined $length; my $offset = 0; while ( $length ) { my $written = syswrite STDOUT, $buffer, $length, $offset; $length -= $written; $offset += $written; } } close $READHANDLE; print \n; You will want to remove this as it will be an addition to the actual data which can break some formats. exit; The above cod was tested in both Mozilla and IE browers with the same results. It appears I'm missing some statement that should follow the Content-Disposition statement. Does this hit the mark? http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regd. cgi -apache
[EMAIL PROTECTED] wrote: Hi perlers I am having IBM http server installed on my unix machine.. But ro run cgi perl files I think we need apache. Though http server supports apache functions. But stillI am facing problem could u please tell me what to do Actuallly I am totally new to cgi programming in Perl so need help.. Or I have to install the apache also on my machine? Plz suggest me.. I am assuming IBM's server isn't open? If you are having it installed, you should probably consult IBM's tech support. Assuming their web server is worth anything you shouldn't need to run Apache too. If you are going to run Apache, I would stick with a single web server and scrap the IBM one as well. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Forcing a save as' dialogue box to come up on left click
Tony Frasketi wrote: Hello Listers I'm trying to find a way to force a download dialogue box to come up when the user clicks on a link on a web page (the link will primarily be for htm, .txt files on the server). Normally when the user left clikcs on the link the .htm or .txt file appears in the browser. And also normally when the user right clicks on the link, he is given the choice to 'Save Link Target as' in order to download the file. What I'm looking for is to avoid right clicking and choosing to save the file Is there a way to implement left clicking the link and automatically bringing up a Save As dialogue box? I've googled for such things as mime type download save as etc but came up with dead ends TIA Tony Frasketi Most browsers will provide this functionality if the return header is application/octet-stream rather than text/html or the like. In the case of IE you may have to fool the browser into thinking it is getting something different than it is based on the URL, because it likes to look there for a file extension to determine the file type too. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: problems with CGI.pm upload feature
Bill Stephenson wrote: On Sep 16, 2005, at 7:51 PM, Scott R. Godin wrote: Wiggins d'Anconia wrote: Scott R. Godin wrote: script is at http://phpfi.com/78748 I followed the instructions in CGI.pm as best I could, and from what I read the upload() function is supposed to return a filehandle ? (it doesn't say whether this is a direct FH to the tempfile or not) I had dome some preliminary testing with one-liners and was pretty sure this would work, but what I wind up with in the attachment is a file containing the name of the file, not its actual contents. what did I do wrong? I can't figure it out. :/ Possibly used the wrong web browser to upload the file. Not all of them support this feature. Firefox does not. It will however provide the CGI script with the file name. Kindest Regards, -- Bill Stephenson Firefox doesn't support file uploads? I use it all the time to test scripts that accept uploads. Huh? http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: problems with CGI.pm upload feature
Scott R. Godin wrote: script is at http://phpfi.com/78748 I followed the instructions in CGI.pm as best I could, and from what I read the upload() function is supposed to return a filehandle ? (it doesn't say whether this is a direct FH to the tempfile or not) I had dome some preliminary testing with one-liners and was pretty sure this would work, but what I wind up with in the attachment is a file containing the name of the file, not its actual contents. what did I do wrong? I can't figure it out. :/ Just because it is easy to overlook and fairly common, did you include the 'enctype' in the form tag? For instance, [form enctype=multipart/form-data action=/cgi-bin/request method=POST] HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: File Modification Date
Vance M. Allen wrote: I'm trying to find out how to determine the date and/or time that a file was created in a simple procedure. I have heard about a few different libraries but the examples I have found haven't been very useful. The basic purpose I want to do is a simple footer provided by a package module through CGI to inform users of the latest update to the code based on the URL. Something simple saying Version x.xx, Last Modified MM/DD/. which would automatically get the file modified timestamp. I'd prefer to have, if possible, a simple scalar variable to store the date...for example: $modtime = filemoddate_func(filename.cgi); If anyone can help me with the libraries I need to use for this (if any special), and a code snippet if possible, I'd really appreciate it. Thanks! Vance Generally this type of information is provided by Cstat, see, perldoc -f stat For the details. To get the modification time for example you could use something like, my $mod_time = (stat 'filename.cgi')[9]; File creation time is rarely if ever available. Obviously you could wrap the above in a sub, but I suspect there isn't a lot of reason to since it is so short anyways. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Why wont this work? Package require question
Luinrandir wrote: $Player{Location}=Inn You are missing a semi-colon, and there is no reason to use double quotes above. require '$Player{Location}.pl'; #no error here, I think. Single quotes don't interpolate. '$Player{Location}'::HTML(); #error occurs here I'd hate to have to make a big if then else just to do this... Not sure what that would be aimed at. http://danconia.org Thanks Luinrandir -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Why wont this work? Package require question
No need to top post, please don't. Luinrandir wrote: Ok.. and i'm actually going to top post for this... when done is should read $Player{Location}=Inn; require '$Player{Location}.pl'; whixh is the same as require 'Inn.pl'; Same problems exist. Single quotes do NOT interpolate, meaning the value of the variable is not replaced, the variable name itself is being used. So Perl is looking for a file called $Player{Location}.pl which probably doesn't exist. Double quotes DO interpolate, but when you don't need to interpolate use single quotes. So, $Player{Location} = 'Inn'; # single quotes are fine require $Player{Location}.pl; # double quotes for interpolation Theoretically this should work if I remember 'require's specs correctly. Though these days I would switch to 'use' and bring in both libraries unless they are really huge, and not worry about the run time consequences. and then '$Player{Location}'::HTML(); Again, you would need to use double quotes, but in the above you might be able to get away with or may be required to avoid stringification. So either, $Player{Location}::HTML(); or $Player{Location}::HTML(); Either way single quotes will NOT work. The above also assumes that you have included the proper package statements in the required library. perldoc -f package which is the same as Inn::HTML(); Do i have the vars correct so that if I want to change $Player{Location}=Inn; to $Player{Location}=Gate; the program would require the correct package require Gate.pl and the call on the sub HTML in that package? Gate::HTML(); Not the vars that matter, it is the quoting. http://danconia.org [snip old messages] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Comparing file contents (code included)
Robert wrote: When Perl is doing this comparison is it doing it line by line (like an actual DIFF) or is it putting the lines into an array and the checking that array against the second file? Well yes and no, to both. It is storing the lines temporarily, but it is storing them to a hash, not an array. Then it is checking them line by line. Depending on the purposes there are several large differences between the code and a DIFF. For one, order is not maintained in a hash so it is really checking just to see if the line did exist in the first file, rather than that they are in the same order, which matters to a diff. Secondly it is checking to see if that line is in fact Perly true, so if a line consisted of just a 0 it would be false and return a false negative. Thirdly, because a hash can only store a key a single time then duplicated lines would be unconditionally kept, and no indication provided, even if for example the second file contained 43 copies of the same line and the first file only contained 1. There are other issues, for instance the first three opens check for success but the others don't. Additionally there is absolutely no reason to open/close the file within the loops, this really kills efficiency. If you are really looking for a diff creator there are several good ones on CPAN. http://danconia.org use strict; use warnings; open VASH, vash.txt or die Can't open the file: $!\n; open MONH, monh.txt or die Can't open the file: $!\n; open MANI, mani.txt or die Can't open the file: $!\n; my %dict; $dict{$_} = 1 while VASH; # This will insert in the text files the lines that are in # the Vashon but not in the Monhegan while (MONH) { open VASH2MONH, VASH2MONH.TXT; print VASH2MONH if !$dict{$_}; close VASH2MONH; } print Mohegan comparison is done.\n; # This will insert in the text files the lines that are in # the Vashon but not in the Manitou while (MANI) { open VASH2MANI, VASH2MANI.TXT; print VASH2MANI if !$dict{$_}; close VASH2MANI; } print Manitou comparison is done.\n; close MANI; close MONH; close VASH; print Comparison is completed.\n; It works. I am just wondering in what fashion it IS working. Robert -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Comparing file contents (code included)
John W. Krahn wrote: Wiggins d'Anconia wrote: Robert wrote: When Perl is doing this comparison is it doing it line by line (like an actual DIFF) or is it putting the lines into an array and the checking that array against the second file? Well yes and no, to both. It is storing the lines temporarily, but it is storing them to a hash, not an array. Then it is checking them line by line. Depending on the purposes there are several large differences between the code and a DIFF. For one, order is not maintained in a hash so it is really checking just to see if the line did exist in the first file, rather than that they are in the same order, which matters to a diff. Secondly it is checking to see if that line is in fact Perly true, so if a line consisted of just a 0 it would be false and return a false negative. No, the line contents are stored in the hash key but the check is done on the hash value which is always one. John Ah, good point. Attention to detail http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sendmail, etc.
zentara wrote: On Thu, 8 Sep 2005 19:31:11 -0700 (PDT), [EMAIL PROTECTED] (Matthew Sacks) wrote: Greetings, I want to send mail from my perl code. (Boy, that's really unusual) I am thinking using mail::mailer. I need a bit more info than what I have so far found in the online documentation (perldoc -q mail). Where I can I find some advice? E.G., there is always an example of code that defines a $to argument. but can $to be a list of addresses? (a group, that is). Can $to be a list of 100 email addresses? Do I have to think about tuning my sendmail daemon? It is starting automatically upon boot, of course -matthew sacks Peace Corps Volunteer [EMAIL PROTECTED] This is untested, and there may be a more efficient way, like not opening and closing SENDMAIL each time thru the loop. But this should work. Ugh, stick with a module. Dealing with sendmail directly is a giant hassle, formatting complex messages by hand is an even bigger hassle. Enhancing the code to send attachments which is almost always the next question is one that should never be answered. This is a wheel that has been re-invented enough. The code that was below *may* have been sufficient but it doesn't have proper error handling and isn't as portable as using most of the mail modules available on CPAN. http://danconia.org Just take the following snippet, and loop thru it for each value of @to. [snip code, use a module] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Exact matching using GREP.
Please bottom post Sara wrote: No, it's not working, probably you didnt' get my question. How is it not working now? What Ovid sent is exactly what I would have answered so you probably need to provide more information. You mention man pages and switches to grep, there are two greps here, 1) the command line program used for searching files which is where your -x, etc. come in and 2) 'grep' the function which is a Perl built-in. For the docs for it, you need to check: perldoc -f grep They are very different things. http://danconia.org Anyways, thanks for a prompt reply. Sara. - Original Message - From: Ovid [EMAIL PROTECTED] To: beginners-cgi@perl.org Sent: Friday, September 09, 2005 12:01 AM Subject: Re: Exact matching using GREP. --- Sara [EMAIL PROTECTED] wrote: while (my $row = $sth-fetchrow_hashref) { if (grep /$row-{CAT_TITLE}/, @present) { #matching title with @present elements print $row-{CAT_TITLE}; } Question is how to do EXACT matching using GREP? because the above code prints every element from array for 'php' if the $row-{CAT_TITLE} is 'php' it prints php/counters, php/forums and every element containing php. Assuming I understood your question correctly: if (grep { $_ eq $row-{CAT_TITLE} } @present) { # do something } Cheers, Ovid -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: %ENV
Please bottom post Tony Frasketi wrote: I've had problems with this in this the past and found your solution to work as long as I run my script from the bash command line. However if the script is run from a web page, I still do not get the value of the environment variable that I had set from the bash prompt or even in the .profile file. Can you shed some light on why the variables do not show up on the web page? TIA tony The key is what environment the script inherits from. In the case of your script running from the command line it is inheriting the environment of the shell, so your .profile and soft settings are inherited. But when run as CGI it is inheriting the environment of the web server, which generally controls the environment closely. Most web servers I suspect, and know Apache does for sure, allow you to add arbitrary environment settings in the configuration. See: http://httpd.apache.org/docs/1.3/env.html This is the same reason why there are user permission/ownership requirements, because your script isn't running (necessarily) as who created it, but is instead running as the user running the webserver (often nobody/apache/www). The same applies when doing forking operations from within your script, the fork inherits the same environment as your Perl script, and so on... http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: nice low cost ISP with support for mod_perl, any suggestions
Adriano Ferreira wrote: I am on the verge of trying to deploy a small web application for small business. I would like to see it working preferably under mod_perl. Does anyone has suggestions about possible providers with a good compromise between service quality and cost? As it is directed to small business, it won't be very demanding on bandwidth or storage and cannot be expensive. Regards, Adriano. I have come to prefer ISPs that provide VPS (Virtual Private Servers) accounts. This gives you far greater control over the whole installation, essentially giving you root access. In most cases you can install your own software and have complete control over the Apache config. Right now I use Westhost (http://www.westhost.net) (I am not an employee, rep, etc. but WH is the first low cost ISP I have actually been happy with), but there are more and more springing up. There is also an open source VPS that some use, Westhost does not, so I might look at one of them soon. Good luck, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Force a file download for link
Denzil Kruse wrote: --- Bob Showalter [EMAIL PROTECTED] wrote: snip use CGI qw(:standard); open FILE, ...blah blah... print header('application/octet-stream'); print while FILE; Thanks for the help Bob! Is there another way besides the content-disposition to specify an attachment or filename? I was trying to find a way to get a file download box to come up to ask where to save the file on their local computer. With just the above, it will display it in the browser, and my users will just go...huh? Denzil The 'header' function can take a key/value list of arguments to include additional header lines. So you can pass your content-disposition header as you had it before. The key here is that the content type be set to 'application/octet-stream' and that the disposition header will only work if the client understands it, but in most cases it is worth a shot. In one my libraries I use, my %header_options = ( -Content_Type = 'application/octet-stream', -Content_Length = $content_length, ); if (defined $self-{'filename'} and $self-{'filename'} ne '') { $header_options{-Content_Disposition} = attachment; filename=\$self-{'filename'}\; } It seems to have worked for me. Obviously you need to replace $self-{'filename'} with your variable, and preferably set $content_length with the file size. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Escaping with tr
Eric Walker wrote: On Tuesday 30 August 2005 04:16 pm, Bernard van de Koppel wrote: bla bla;bla bla;bla bla cat test.file | sed 's/\//g' editedfile Quick someone get the can of UUoC Be Gone ... ;-) http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Escaping with tr
Scott Taylor wrote: Hi, How can I get all the characters out of a csv file. Input looks like bla bla;bla bla;bla bla and it has to look like bla bla;bla bla; bla bla I tried $text=~ tr(#\##); but perl keeps complaining about Might be a runaway multi-line ;; On a more serious note. Simply removing *all* double quotes can be a dangerous proposition unless your data really does look like bla bla which I somewhat doubt. Usually a delimited file like this will quote specific fields because they may contain the delimiter, in this case a semi-colon. Are you sure bla bla can't be blah; blah blah, and then in the future need to still be delimited by the semi-colon? Just checking... http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: encrypt the password stored in a file
JupiterHost.Net wrote: Ken Perl wrote: The password used to access a ftp server is stored in a text file, the perl program gets the password from the file, the pass it to the ftp server for logon, this is the background. The requirement is encrypt the password store in a more secure way, and the perl program could still use the encrypted password to logon the server. what algorithm should be used in this task? Any Crypt:: modules would help but then the way to unencrypt it is still in a file. You be better off doing: my $password = 'plaintext'; chown user:user config.pm chmod 600 config.pm that way only the user can read it so it can safely be in plain text. Obscuring it is a lame way to do it because any moron with half sense can figure out how you unobscure it if they have access to the file anyway. Permissions, permission, permissions :) HTH :) Considering it is FTP who cares about permissions too. It is an insecure protocol to begin with, the password is sniffable during transmission anyways, really the words FTP and secure don't belong in a sentence together, unless they are included with the word NOT. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Need a list of files in a dir.
Please bottom post... Daniel Kurtz wrote: Ooh ooh ooh! One I know! open(COMMAND, dir |); @files = COMMAND; Sort of, while that *may* work it doesn't have proper error checking, is less secure, less efficient, and less portable than many other ways, especially those already provided. This is my same rant as in the past, check the archives if you want the real details, but shelling out is an *absolute* last resort. Perl provides built-in functions to handle this, in cases where it does it is never faster, safer, or more portable to shell out. http://danconia.org Daniel -Original Message- From: Luinrandir [mailto:[EMAIL PROTECTED] Sent: Thursday, August 25, 2005 21:33 To: beginners@perl.org Subject: Need a list of files in a dir. How do I get the list of files in a DIR and put in an array? I'm drawing a blank on my search for this. thanks Lou -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Directories into arrays, again.
Daniel Kurtz wrote: From: Daniel Kurtz [mailto:[EMAIL PROTECTED] Why does @after end up looking exactly like @before? Is there some buffering going on here? And if so, how do I clear it? Never mind, I figured it out. The file copying operation is another shell operation (c'mon, I'm a newby, and I've only read as far as perlopentut!) and the file handle needs to be closed before the second opendir(). daniel Ok, but that is why you are here to learn. And a reason why using a shell command to copy a file is a bad idea. You didn't do any error checking, so you didn't know where your problem was. I assume you are using 'strict' and 'warnings'. If you aren't, you need to be, and want to be. If you are reading a book, and it hasn't advised you to do so, get a new book, most likely the Llama. If you are reading the perldocs directly, then I would suggest getting the Llama as it will make for much better use of your time. opendir DIR1, '.' or die Can't open directory for reading: $!; In the above, you don't need the extra parens, there is no need to use double quotes unless you are using interpolation and you weren't, so I switched those to singles. And any operation that could fail should be checked for failure, in the above case opendir will return nothing if it fails, so we tack on a message, we include $! to learn *why* it failed. my @before = readdir DIR1; Declare our variables with the proper scope. closedir DIR1; # Execute a command that backs up every file in the directory # with a .bak extension. Here I would suggest using the File::Copy module, as it provides a convenient 'copy' function which is all you are really doing. It is also designed to be as portable as possible, and happens to be standard on newer Perl versions. use File::Copy; foreach my $file (@before) { if (-f $file) { copy($file, $file\.bak) or die Can't backup file: $!; } } opendir DIR2, '.' or die Can't open directory for reading a second time: $!; my @after = readdir DIR2; closedir DIR2; No need for shell commands... perldoc -f opendir perldoc -f readdir perldoc -f closedir perldoc File::Copy perldoc -f -e perldoc strict perldoc warnings As an aside, if you must use a shell command you are better off sticking with system, until you need the output which is provided by backticks, only use the piped open form when you need to communicate with the command you are running. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: odd benchmark result, map vs foreach
Scott R. Godin wrote: Wiggins d'Anconia wrote: Your benchmark isn't controlled. In the first instance you are doing a ++ on what amounts to a scalar getting autovivified, in the second instance you are assigning a pair of values to a list then autovivifying it. It isn't necessarily the map vs. foreach that is causing your difference. I think for your benchmark to be accurate you are going to have to control the actions taken in the loop, otherwise they affect the accuracy of your benchmark. mm this may be true, but realistically, that is how I'd write them in code I actually use -- so it behooves me to test them the way I'd normally be using them.. not under artificial circumstances in ways I normally wouldn't write code. I see what you're saying and it makes sense, but in this instance I'm more interested in seeing the results of the idiomatic expression of the end result. :) Right, I was just being strict about your wording. You declared that the foreach was faster than map, but strictly speaking it should have been the way I used foreach was faster than the way I used map, which I wouldn't have argued with. And I am only being that strict because this is an open, archived forum where there are plenty of people that wouldn't have recognized the difference and may have taken you as strictly as I did on purpose, just because they didn't know better. As far as I am concerned write your code however you wish, make it the fastest to read... http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Program is exiting on a failure
Chris Lyon wrote: I seem to be erroring out @ the $session-login portion of my program because the module that I am call is saying the password/username is bad. How do I trap the error and exit cleanly without just dumping from the application: login failed: access denied or bad username at ./cisco.pl line 47 $session = Net::Telnet::Cisco-new(Host = $ip); $session-login($login, $password); You may want to check the 'errmode' method of Net::Telnet. Otherwise you can catch the die in the normal Perl exception handling way, perldoc -f eval my $return = eval { # some code that might die }; if ($@) { print Uh oh, croaked leaving only: $@; } # code after not croaking http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $ENV{'HTTP_REFERER'}
Denzil Kruse wrote: Hi, I want to know the web site that someone came from, and so I was planning on reading $ENV{'HTTP_REFERER'} to figure it out. How reliable is that? Do browsers or other situations block it or obfuscate it? Is there another way to do it or any other issues involved? I'm using apache on red hat. Thanks, Denzil Depends on your definition of reliable. From experience it would seem most browsers set it pretty reliably. Having said that, it is just a value passed as part of the HTTP request so anyone can spoof it at anytime, so relying on it from a security stand point, well, isn't secure. I imagine if you are doing something where someone can benefit from obfuscating it, they will. If you want to use it for ease of UI handling (aka redirects, prepopulating fields, marketing metrics) I think you are safe. HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: two way piped open
Bryan R Harris wrote: I'd like to open 2-way pipe to a tool that we have here. It's called yprtool and once it's open, you give it 3 numbers to its STDIN and it spits out 3 numbers to its STDOUT. It stays open until you ctrl-c it. What's the correct syntax for opening something like this? This doesn't work: ** $yprtool = '/Users/bh/Library/models/yprtool'; open(YPRTOOL, +$yprtool|) or die open error blah; print YPRTOOL $a $b $c\n; $return = YPRTOOL; close(YPRTOOL) or die a cruel death; ** I think the problem is in the +, but I'm not sure. - B Check out the IPC::Open2 and IPC::Open3 modules, they are standard. perldoc IPC::Open2 perldoc IPC::Open3 Additionally there is good information available in, perldoc perlipc http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: odd benchmark result, map vs foreach
Scott R. Godin wrote: Interesting .. I would have thought that map would be faster, but it appears that foreach is, in this instance. curious.. :) 4:52pm {193} localhost:/home/webadmin/$ perl bench.pl Benchmark: running Foreach, Map for at least 5 CPU seconds... Foreach: 9 wallclock secs ( 5.24 usr + 0.00 sys = 5.24 CPU) @ 35906.30/s (n=188149) Map: 11 wallclock secs ( 5.29 usr + 0.01 sys = 5.30 CPU) @ 24095.47/s (n=127706) 4:54pm {194} localhost:/home/webadmin/$ cat bench.pl #!/usr/bin/perl use warnings; use strict; use Benchmark qw(timethese); timethese( -5, { Foreach = sub { my %nr; $nr{$_}++ foreach qw{ shipto_company shipto_email billto_company billto_email same_bill_ship rkh_quantity rkp_quantity rmh_quantity rmp_quantity rbh_quantity rbp_quantity ship_on_account shipping_id_number order_number }; }, Map = sub { my %nr = map {$_ = 1} qw{ shipto_company shipto_email billto_company billto_email same_bill_ship rkh_quantity rkp_quantity rmh_quantity rmp_quantity rbh_quantity rbp_quantity ship_on_account shipping_id_number order_number }; }, } ); Your benchmark isn't controlled. In the first instance you are doing a ++ on what amounts to a scalar getting autovivified, in the second instance you are assigning a pair of values to a list then autovivifying it. It isn't necessarily the map vs. foreach that is causing your difference. I think for your benchmark to be accurate you are going to have to control the actions taken in the loop, otherwise they affect the accuracy of your benchmark. http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: using system to run ssh $host command
grover mitchell wrote: Hi, I am trying to use system to run a command on a remote machine. system ssh, $remote_host[0], sudo, -u, nobody, /usr/bin/remote_command, --arg1, $arg1, --arg2, $arg2; The problem I run into is that perl will ssh into the remote host and give me a shell there, instead of running the remote command on the remote system. When I exit, perl will then try and run the remote command on my local host. Is there an easy way to accomplish this task using system? Thanks for any help. I haven't tested, but there haven't been any other responders yet so I thought I would chime in. Have you tried the one argument form of Csystem? There is the potential for the above to be getting screwed up by the 'exec' rather than the 'execvp' mentioned in, perldoc -f system I suppose. Try joining all of your arguments along with the command into a single string passed to system and see if that helps. Of course you could always try Net::SSH::Perl as a substitute. You also ought to consider using a full path to ssh, and I assume the above is just a snippet of a larger set of code that does proper error checking/handling per the Csystem docs ;-)... HTH, http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Shell output
Scott Taylor wrote: Hello all, I have a CGI script that I need to display the output of a shell program, basically a simple C program that parses some text. The output is right to the browser, and I don't want it to be creating any new files or anything. I have a data field that has a blob and that blob needs to be parsed and the output returned to the browser. What is a good way to do this: while ( my ($row ) = $sth-fetchrow_hashref ) { my $raw_data = $row-{BLOB}; my $parsed_data = system (echo $raw_data|pasrer); ... } of course that doesn't work, but what would be the right way to do it? Cheers. -- Scott You should have a look at the section Pipe Opens in, perldoc perlopentut Should be what you are looking for. I do assume you have a good reason for writing the parser in C http://danconia.org -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response