Re: Perl Frameworks?
Tom Smith wrote: I'm curious... With all the buzz about MVC frameworks now, what does Perl have for this? The only two that I'm aware of are Gantry and Catalyst (Catalyst appears to be more complete)--are there others? And which one would be considered the defacto standard (most widely used or accepted)? I'm not qualified to speak on the merits of the particular frameworks, but the ones I know of are listed below. Jifty is the youngest, and is similar to Ruby on Rails, I think. Catalyst has a very active community (not to say more active than the other, but I know that it has a very active mailing list.) I'd check their websites. Join their mailing lists. Read tutorials. Ask questions on their respective lists. Then make your own decision. Jifty http://jifty.org/view/HomePage Catalyst http://www.catalystframework.org/ Maypole http://maypole.perl.org/ Gantry http://www.usegantry.org/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Trouble with variable scoping
Roman Daszczyszak wrote: In my perl script, I have a global variable called @excludedIPAddresses, declared at the top of the script using my: [...] When I run this, I get an error Can't localize lexical variable. I understand that it's because the variable is declared using my; what I don't understand is why, or what I should declare the variable as, since if I leave out my I get an error using use strict. The Cmy and Cour declarators have less to do with scope than with storage and access. Variables declared with Cmy are limited to the scope in which they are declared and any inner scopes, and are known as local or lexical variables. They may be re-declared within an inner scope, in which case the inner scope masks the outer, but the outer variable still exists, it retains its value, and it will be accessible again when control returns to the outer scope. For Cmy variables, storage is tied to the scope in which the variable is declared, in a scratchpad that is thrown away at the end of the scope. Cmy variables can also be global variables when declared in a large scope. Variables declared with Cour are tied to a package and are stored as part of the package, and are known as package variables. They are accessible anywhere in the package by using the short name or outside the package by using the fully qualified name (i.e. type-glyphpackage-name::variable-name). You can simulate the scoping rules of Cmy variables with the Clocal function(?). Clocal creates a copy of the _value_ of the outer package variable that masks any previous value. The new _value_ exists only within the scope in which the Clocal function was used. Clocal does not declare a variable unless you run without the 'strict' pragma. Without 'strict' it creates the package variable for you, but when using 'strict', it generates an error requiring you to either declare it with Cour or to fully qualify it with the package name. Mixing variables of the same name with different storage is where things are sometimes less clear. (And some of the rules have changed slightly through different revisions of perl.) So, generally you should avoid using variables of the same name with different storage declarators. When Perl sees code like: use strict; my $foo; local $foo; It first creates the lexical variable $foo. It then evaluates the call to Clocal by first trying to resolve the name of the variable it refers to. Since the only $foo it knows about is a lexical variable, it warns you that you are trying to use Clocal on a lexical variable. If you declare a package variable: use strict; my $foo; our $foo; local $foo; Perl will resolve the name $foo referenced in the call to Clocal to the package variable and will happily use it. IOW, the error comes about during the process of trying to resolve the variable name. If the variable name resolves to the wrong type of variable, you get an error. You could also help Perl to resolve the name by fully qualifying it: use strict; my $foo; local $PackageName::foo; __END__ Regards, Randy. -- 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 variable scoping
John W. Krahn wrote: Randy W. Sims wrote: Roman Daszczyszak wrote: In my perl script, I have a global variable called @excludedIPAddresses, declared at the top of the script using my: [...] When I run this, I get an error Can't localize lexical variable. I understand that it's because the variable is declared using my; what I don't understand is why, or what I should declare the variable as, since if I leave out my I get an error using use strict. The Cmy and Cour declarators have less to do with scope than with storage and access. Variables declared with Cmy are limited to the scope in which they are declared and any inner scopes, and are known as local or lexical variables. They may be re-declared within an inner scope, in which case the inner scope masks the outer, but the outer variable still exists, it retains its value, and it will be accessible again when control returns to the outer scope. For Cmy variables, storage is tied to the scope in which the variable is declared, in a scratchpad that is thrown away at the end of the scope. Cmy variables can also be global variables when declared in a large scope. Variables declared with Cour are tied to a package and are stored as part of the package, and are known as package variables. They are accessible anywhere in the package by using the short name or outside the package by using the fully qualified name (i.e. type-glyphpackage-name::variable-name). Variables declared with our() have the same scoping rules as variables declared with my(). $ perl -le' use warnings; use strict; package me; our $x = q/our/; my $y = q/my/; package main; print for $x, $y; ' our my Sort of. This is one of Perl's weird features. I'm not quite sure how to define the behavior... The Cmy variable is scoped from the point of declaration to the end of the enclosing scope, which, in this case, is file scope. This is not unusual. The Cour declaration creates the package variable $me::x. If you add to the end of your example: use Data::Dumper; print Dumper \%me::; You'll notice that the symbol 'x' has been created as an alias for *me::x. So with Cour we are still talking about a package variable. What I'm unsure of is how the alias is set up. There is no symbol 'x' in main: print Dumper \%:: Both $x and $y are only valid from the point they are declared until the end of the file. If package 'me' were defined in a different file, both $x and $y would not be accessible from package 'main'. So I guess I don't really know technically how $x is resolved to $me::x from within main. Maybe it's quietly added to the lexical scratchpad for the file scope as an alias to the package symbol of the same name? If that is the case, then Cour and Cmy would always share the same scoping, but have different storage and access semantics. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: golf
Chad Perrin wrote: This is kind of a frivolous question, but . . . is there some way to golf this? while () { s/\n/ /; print; } perl -pl04 -e1 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: golf
Chad Perrin wrote: This is kind of a frivolous question, but . . . is there some way to golf this? while () { s/\n/ /; print; } perl -pl40 -e1 -- 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 tell perl to look for where a new module is installed
chen li wrote: Hi all, Thank you all for reply my post in advance. I install in new module like this: c:/perl/local/new.pm. How should tell the perl to look at it in addition to the default paths? Set the environment variable PERL5LIB to the additional paths. On the command line: `set PERL5LIB=C:\perl\local` or in the system control panel applet (hold Windows key and press break), select advanced tab, hit the Environment Variables button. Then create a new system or user variable. I have a number of perls on my machines, and switch back and forth by manipulating the PATH and PERL5LIB all the time. This is the easiest way to do it. ( You can also do it by setting various entries in the registry, see perl-src\win32\win32.c in functions win32_get_privlib(), win32_get_xlib() ) Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regex matching conditionally
JupiterHost.Net wrote: Howdy list, I'm trying to see if I can do this in one regex instead of multiple stage, mainly for educational purposes since I already have it in multipel steps. I am trygin to get each string between { and } where the {} occurs between double quotes. So with file.optcondition={/Root/Get/Peter}ampc={/Root/Get/do}bleah={/Root/Blah} I want /Root/Get/Peter and /Root/Get/do Seems I could do it if I could do the first grouping wihtout using the matching () but I dont; thinkm that is possible, any ideas woudl be great! Danke! #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $string = q(file.optcondition={/Root/Get/Peter}ampc={/Root/Get/do}bleah={/Root/Blah}); Not what you asked for, but probably more correct: my @matches; use Regexp::Common; my @quoted = ($string =~ /$RE{quoted}/g); foreach my $quoted ( @quoted ) { push( @matches, ($quoted =~ /$RE{balanced}{-parens='{}'}/g) ); } print join \n, @matches; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: about deleting subroutine
Jennifer Garner wrote: hi,lists, Hi Jennifer, I have seen this thread on perlmonk,and it make me confused too.Can anyone here explain that?Thanks. Quote: --- Basically, deleting subroutines from a symbol table seems a bit buggy, but I don't know if this behavior is documented or not. Bug #37128: undefing *foo{CODE} does not fully work http://rt.perl.org/rt3/Ticket/Display.html?id=37128 Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: about deleting subroutine
Jennifer Garner wrote: hi,Randys, Bug #37128: undefing *foo{CODE} does not fully work http://rt.perl.org/rt3/Ticket/Display.html?id=37128 When I try to access that url,it require me to be verified by username and passwd. So I can't access that url. username: guest passwd: guest Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Shortest One-liner to Rename Files
Wijaya Edward wrote: Hi all, I have a snippet that rename files from: sth.txt.out into sth.out Now I am really curious how can I make this oneliner even shorter: $ perl -e ' for(glob (*.txt.out)){ $out = $_; $out =~ s/\.txt(\.out)/\.out/; rename ($_,$out); }' perl -e '/(.*)\.txt(\.out)$/rename$_,qq($1$2)for*.txt.out' -- 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 glob() ?
Gustav Wiberg wrote: This seems totally meaningless, but what would $list = glob('*.txt') return? Try it. g -- 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 perldoc ?
Jeff 'japhy' Pinyan wrote: On Oct 19, Brian Volk said: Is there a perldoc that will list the available arguments and there meanings for perl-one-liners? Yes. To try and figure out what perldoc to look at for a given topic, do: perldoc perldoc You mean `perldoc perl` ? ;) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Book Recommendation: Secure web programming ?
I know perl. I know some basics of web/CGI programming, but haven't done anything where security really matters. Could anyone recommend books or references that discuss real-world web programming, that show the right way to create secure sites? Topics like creating logins, varying levels of access rights (some can edit, some can view, some have limited views), different methods of storing information storing user data (plain file, DBM, DBMS; strengths/weaknesses), what issues arise in using web hosting vs having your own server. Also, are there any particularly good general web development books you highly recommend? Thanks, Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: tricky list comparison problem
Jason Ross wrote: Anyway, the issue I have is that I need to determine where there are gaps between the first sector and last sector (on the entire disk, not on a given partition). So, for example, using the sample data below, I want to return 2097415 - 69078878 as available sectors. Hi Jason, I find the Set::IntSpan module very useful for this type of thing: #!/usr/bin/perl use strict; use warnings; use Set::IntSpan; # the last sector on disk my $end_sect = 71127179; # The complete range of sectors on the disk my $range = Set::IntSpan-new( 0-$end_sect ); # The ranges of used sectors my $used = Set::IntSpan-new( '0-1048706,1048707-2097414,69078879-71127179' ); # Calculates the remaining unused sectors my $unused = $range-diff( $used ); print $unused-run_list; __END__ Sample data I called this file in. If you change the name, you'll need to alter the last line of the script -- * /dev/dsk/c1t0d0s2 partition map * * Dimensions: * 512 bytes/sector * 107 sectors/track * 27 tracks/cylinder *2889 sectors/cylinder * 24622 cylinders * 24620 accessible cylinders * * Flags: * 1: unmountable * 10: read-only * * First SectorLast * Partition Tag FlagsSector CountSector Mount Directory 0 2001048707 1048707 2097414 / 1 301 0 1048707 1048706 2 500 0 71127180 71127179 7 800 69078879 2048301 71127179 /export/home -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Please Help!!! Newbie Question
Perl wrote: Hi List, I have this script which actually returns the value of the filename with extension but If the file name is something like c:\projects\text 009.txt (having a space in filename which is common in windows). This script only returns text instead of returning full name of file. Hi Perl, Are you quoting the filename on the command line? Most shells split arguments on whitespace. In your example $ARGV[0] contains c:\projects\text, and $ARGV[1] contains 009.txt. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: expanding Ranges
N. Ganesh Babu wrote: Dear All, input: aud=1-3T cpn=1-3,4,5,6-106 bnd=1-3TC output aud=1,2,3T cpn=1,2,3,4,5,6,7,8,9,106 bnd=1,2,3TC How can it be achieved in regular expression?. Or any other means is easy. use Set::IntSpan; my $set = Set::IntSpan-new('1-3,4,5,6-10'); my @elems = $set-elements; print join( ',', @elems ), \n; __END__ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: ideintifying whether a module is already installed or not
Edward Wijaya wrote: On Sun, 27 Mar 2005 20:28:42 +0800, Manish Sapariya [EMAIL PROTECTED] wrote: Hi list, Hi How do I know whether a given module is installed on machine or not? perl -MModule::Name -e 'print it is installed\n;' or it's simpler variant perl -MModule::Name -e1 or even perldoc -l Module::Name -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: ideintifying whether a module is already installed or not
Offer Kaye wrote: On Sun, 27 Mar 2005 18:19:22 +0300, Octavian Rasnita wrote: Have you noticed that -l parameter? If it is used, the perldoc command just show the directory where the module is installed. Teddy Sigh... did you even try out my example? He most likely did. Your example works fine here because there is pod in that file at least in some versions. But you are correct that files without pod will simply generate a No documentation found... error. I've never ran into that problem, but then I don't use that trick too much prefering the more idiomatic 'perl -MModule -e1'. I saw the perldoc trick mentioned on P5P several years ago, so I usually mention it when this topic comes up as an interesting tidbit. Randy. Please read my answer *carefully*, the perldoc Pod::Perldoc command will return 'No documentation found for Pod::Perldoc.' regardless of whether you use the -l switch or not, since Pod::Perldoc *has no pod documentation*. However, Pod::Perldoc *is* an installed module. So using perldoc -l Module::Name as a means to finding out whether or not a module is installed is not a very robust way of doing it. The other ways posted by various people are much better. Cheers, -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regex for l33t speak
Andrew Gaffney wrote: Wow, this is more difficult than I first thought. Not really. Just for kicks here is a simple driver: #!/usr/bin/perl use strict; use warnings; use Leetspeak; # $Leetspeak::DEBUG = 1; my $word = shift( @ARGV ); my $l33t = Leetspeak-new(); my $translation = $l33t-translate( $word ); if ( $translation ) { print $word = , $translation , \n; } else { print not found\n; } __END__ for the following module: package Leetspeak; use strict; use warnings; our $DEBUG = 0; sub new { my $package = shift; my %args = @_; my $dict = (grep defined -e, ( $args{dict}, '/usr/share/dict/words' ))[0]; my %data = ( dict = $dict ); my $self = bless( \%data, $package ); $self-_read_dict(); return $self; } { my %trans_tbl = ( '@' = [ 'A' ], '$' = [ 'S' ], '+' = [ 'T' ], '0' = { '0' = [ 'O' ], '0r' = [ 'ER' ], }, '1' = [ 'I', 'L' ], '2' = [ 'Z' ], '3' = { '3' = [ 'E' ], '3y3' = [ 'I' ], }, '4' = [ 'A' ], '5' = [ 'S', 'Z' ], '6' = [ 'B', 'G' ], '7' = [ 'T' ], '8' = [ 'B' ], '9' = [ 'P', 'Q' ], 'l' = [ 'I' ], 'p' = { 'p' = [ 'O' ], 'ph' = [ 'F' ], }, 'x' = [ 'CK', 'CKS' ], 'z' = [ 'S' ], ); sub translate { my $self = shift; my $word = shift; my $start = shift || 0; print translate( $word, $start )\n if $DEBUG; return $word if $self-_has_word( $word ); for my $i ( $start .. length( $word ) - 1 ) { my $ch = substr( $word, $i, 1 ); next unless exists( $trans_tbl{$ch} ); my $trans = ( ref( $trans_tbl{$ch} ) eq 'HASH' ) ? $trans_tbl{$ch} : { $ch = $trans_tbl{$ch} }; foreach my $key ( keys( %$trans ) ) { my $key_len = length( $key ); if ( substr( $word, $i, $key_len ) eq $key ) { foreach my $tr ( @{ $trans-{$key} } ) { print substr( $word, $i, 1 ) = $tr\n if $DEBUG; my $new_word = $word; substr( $new_word, $i, $key_len ) = $tr; $new_word = lc( $new_word ); my $offset = $key_len - length( $tr ); $offset ||= 1; my $result = $self-translate( $new_word, $i + $offset ); return $result if $result; } } } } return undef; } } sub dict { return $_[0]-{dict} } sub _read_dict { my $self = shift; my %words; open( my $fh, '', $self-{dict} ) or die $!; while (defined( my $word = $fh )) { chomp( $word ); $words{$word} = 1; } close( $fh ); $self-{words} = \%words; return scalar %words; } sub _has_word { my $self = shift; my $word = shift; return 1 if exists( $self-{words}{$word} ); } 1; __END__ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regex for l33t speak
Oops, I forgot to detab before inlining that, and there was some loose ends. Here it is again inlined and attached. It's not optimized in any way, opting instead for a quick straightforward implementation. Incomplete, possibly buggy, completely undocumented. I didn't write it as a patch for Casey's module because of the requirement for a dictionary file which is fairly standard on unixish, but must be obtained for other OS. package Leetspeak; use strict; use warnings; our $DEBUG = 0; sub new { my $package = shift; my %args = @_; my $dict = (grep defined -e, ( $args{dict}, '/usr/share/dict/words' ))[0]; my %data = ( dict = $dict ); my $self = bless( \%data, $package ); $self-_read_dict(); return $self; } { my %trans_tbl = ( '@' = [ 'A' ], '$' = [ 'S' ], '+' = [ 'T' ], '0' = { '0' = [ 'O' ], '0r' = [ 'ER' ], }, '1' = [ 'I', 'L' ], '2' = [ 'Z' ], '3' = { '3' = [ 'E' ], '3y3' = [ 'I' ], }, '4' = [ 'A' ], '5' = [ 'S', 'Z' ], '6' = [ 'B', 'G' ], '7' = [ 'T' ], '8' = [ 'B' ], '9' = [ 'P', 'Q' ], 'l' = [ 'I' ], 'p' = { 'p' = [ 'O' ], 'ph' = [ 'F' ], }, 'x' = [ 'CK', 'CKS' ], 'z' = [ 'S' ], ); sub translate { my $self = shift; my $word = shift; my $start = shift || 0; print translate( $word, $start )\n if $DEBUG; return $word if $self-_has_word( $word ); for my $i ( $start .. length( $word ) - 1 ) { my $ch = substr( $word, $i, 1 ); next unless exists( $trans_tbl{$ch} ); my $trans = ( ref( $trans_tbl{$ch} ) eq 'HASH' ) ? $trans_tbl{$ch} : { $ch = $trans_tbl{$ch} }; foreach my $key ( keys( %$trans ) ) { my $key_len = length( $key ); if ( substr( $word, $i, $key_len ) eq $key ) { foreach my $tr ( @{ $trans-{$key} } ) { print substr( $word, $i, $key_len ) = $tr\n if $DEBUG; my $new_word = $word; substr( $new_word, $i, $key_len ) = lc( $tr ); my $offset = $key_len - length( $tr ); $offset ||= 1; my $result = $self-translate( $new_word, $i + $offset ); return $result if $result; } } } } return undef; } } sub dict { return $_[0]-{dict} } sub _read_dict { my $self = shift; my %words; open( my $fh, '', $self-{dict} ) or die $!; while (defined( my $word = $fh )) { chomp( $word ); $words{$word} = 1; } close( $fh ); $self-{words} = \%words; return scalar %words; } sub _has_word { my $self = shift; my $word = shift; $word = lc( $word ); return 1 if exists( $self-{words}{$word} ); } 1; Leetspeak.pm Description: Perl program -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regex for l33t speak
Andrew Gaffney wrote: I'm trying to come up with a regex for my IRC bot that detects 1337 (in order to kick them from the channel). I can't seem to come up with one that will have few false positives but also work most of the time. Has anyone done something like this before? Does anyone have any suggestions? Write a converter to translate common symbols to the correct letter. If the translated word is a valid dictionary word, flag it. [EMAIL PROTECTED] 3 = E X = X @ = A m = M P = P 1 = L e = E [EMAIL PROTECTED] = EXAMPLE EXAMPLE is a dictionary word, so [EMAIL PROTECTED] must be leet since the conversion rules produced meaningful results. It's not perfect, but should work with very few if any false positives. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regex for l33t speak
Paul Johnson wrote: On Thu, Mar 24, 2005 at 02:25:19AM -0600, Andrew Gaffney wrote: Randy W. Sims wrote: Andrew Gaffney wrote: I'm trying to come up with a regex for my IRC bot that detects 1337 (in order to kick them from the channel). I can't seem to come up with one that will have few false positives but also work most of the time. Has anyone done something like this before? Does anyone have any suggestions? Write a converter to translate common symbols to the correct letter. If the translated word is a valid dictionary word, flag it. [EMAIL PROTECTED] 3 = E X = X @ = A m = M P = P 1 = L e = E [EMAIL PROTECTED] = EXAMPLE EXAMPLE is a dictionary word, so [EMAIL PROTECTED] must be leet since the conversion rules produced meaningful results. It's not perfect, but should work with very few if any false positives. Thanks for yet another very interesting approach. Check out Lingua::31337 on CPAN. That C really does stand for comprehensive. It works the other way around, ie it converts normal text to 31337, but you coud probably reverse the conversions it uses. Best of all, it's written by the founder of this list (hi Casey!) but I don't think it has ever been plugged here. It's about time that was remedied. I'm sure Casey would be happy to accept a patch to add a 313372text function. The only problem with that is that a dictionary is required for it to work because each symbol can have multiple translations. Taking info from the wikipedia[1]: a final s can be changed to z to get the l33t, but to reverse it you have to check first with the z because it might be an actual z. Then if it is not a dictionary word perform the translation and check for a word ending in s. For example, given the l33t word h4x0rz, an algorithm would have to perform something like the following translations, checking each one till it finds a dictionary entry if any: (done by hand and I don't know much about l33t, so...) h4x0rz h4x0rs h4xorz h4xors h4xerz h4xers h4ck0rz h4ck0rs h4ckorz h4ckors h4ckerz h4ckers h4cks0rz h4cks0rs h4cksorz h4cksors h4ckserz h4cksers hack0rz hack0rs hackorz hackors hackerz hackers = BINGO (More permutations here, but we already found a dictionary word, so we stop.) The basic algorithm for anyone who want to try it, and it's pretty commonly seen in parsing, so it's relatively straigtforward: scan string till you reach the end of a word check dictionary for the word LOOP: back up apply conversion(s) check dictionary repeat until success or no more permutations END LOOP: This would probably make a good QotW, or rather the original question would make a good quiz while the above would be one possible solution. So would implementing an efficient dictionary lookup without loading the entire dictionary in memory. Randy. 1. http://en.wikipedia.org/wiki/Leetspeak -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Accessing the class
Offer Kaye wrote: On Sat, 19 Mar 2005 13:37:17 +0200, Octavian Rasnita wrote: And I don't like to use Package::Name directly because I might need to change its name and then I would need to change that name in many places. So place the package name in a variable, and use that variable in all places. Then you have only 2 places to change - the actual package declaration, and the variable declaration: package Package::Name use strict; use warnings; my $class = Package::Name; Why not just use __PACKAGE__ ? print ok\n if (my $class = Package::Name) eq __PACKAGE__; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Use of uninitialized value
Wagner, David --- Senior Programmer Analyst --- WGO wrote: Daniel Kasak wrote: Hi all. I'm after people's thoughts on Perl's warnings about 'Use of uninitialized value' in various situations ( string comparisons, subroutine entries, etc ). I understand what the warning is for. In my code, it's perfectly OK for my variables to be uninitialised, and is beyond my control anyway - the data is coming from a database, and an undef value is perfectly legal ( NULL fields ). I can make Perl stop complaining about it by placing if() statements around everything, eg: if you are using : use warnings; Then you can use 'no warnings;' just like you would use 'use warnings' to turn off. Then you can use 'use warnings' to get it goint again. The better point might be to surround what you want within {}'s and use your 'no warnings' and once you hit the ending }, then will return to using warnings again. You can be a little more specific with: no warnings qw( uninitialized ); # see `perldoc perllexwarn` You could also use a default value; my $value = fetch_value() || ''; or what most seem to do is combine the tests: if ( defined( $value ) $value eq 'some_value' ) { ... } -- 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 Files in Pairs and Run it Iteratively
Edward Wijaya wrote: How can I make my code above such that it can take all multiple files iteratively? When possible try to use the data and throw it away as soon as possible to avoid high memory usage. For example, your version reads all of both files in to arrays, then creates another array containing the sums. If the individual contents of the file aren't needed beyond summing them, you can do something like below as save the memory. use strict; use warnings; while ( my $basename = shift( @ARGV ) ) { open( my $fa, '', ${basename}.fa ) or die $!; open( my $fb, '', ${basename}.rs ) or do { close( $fa ); die $!; }; while ( !eof( $fa ) !eof( $fb ) ) { chomp( my $la = $fa ); chomp( my $lb = $fb ); print $la + $lb = , $la + $lb, \n; } if ( eof( $fa ) eof( $fb ) ) { print exiting normally.\n; } elsif ( eof( $fa ) ) { print more to read from b\n; } elsif ( eof( $fb ) ) { print more to read from a\n; } else { print this can't happen\n; } close( $fa ); close( $fb ); } __END__ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Design Plugin System
Santiago Hirschfeld wrote: Hi everyone, I'm pretty new to perl and i'm doing a program to organize music, I'd like to make a plugin system for the file formats, so i can just use the formats y ussually have, and not include a long list of use in my main program. I was thinking in create modules in MyProg/AudioFormats/ with names as Ogg.pm and then call them automattically in my main program (which should check for all existing files and then create a hash containing the extentions the plugin module manages and the module name (like ('ogg' = 'Ogg', 'mp3' = 'Mp3',) ) and use some standard subs in every module (get_file_tag, get_know_extentions, set_file_tag). My idea is to call the right get_file_tag for every file, so MyProg::AudioFormats::Ogg::get_file_tag is called when an ogg file is used. And that is what i don't know how to do =) Any ideas? Module::Pluggable http://search.cpan.org/dist/Module-Pluggable/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: uninstalling module
Martin Mrazek wrote: Hello, I have installed PDL module for perl, but something went wrong and I need to reinstall it. Shall I remove the module first and then install again? How to remove it? It depends on how it was installed. Normally, from the directory of the distribution (./PDL): perl Makefile.PL make uninstall -or- perl Makefile.PL make test make install UNINST=1 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Input a password from STDIN
Xiaofang Zhou wrote: Anyone can help me in this?. When running $password = STDIN; the password will show on the console windows as user type in. Is it possible for perl to read from keyboard directly, without echo to the console window? perldoc -q password -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Checking last character of string for punctuation
Chris Schults wrote: Thanks to the people who promptly replied. I have two quick follow-up questions: 1) What does s/\s*$/\./ do? (see email below) It effectively puts a period at the end of the string, while deleting any extra spaces at the end. 2) What are the differences between: $string .= '.' unless $string =~ /[$!.]+$/; (suggested in another email) literally: append (.=) a period to $string if $string ends with one or more of dollar ($), exclamation (!), or period (.). and $title =~ s/\s*$/\./ unless $title =~ /[!?.]\s*$/; literally: replace zero or more spaces just before the end of $title, along with the psuedo end of line token ($) with a period Unless $title ends with a single exclamation (!), question (?), or a period (.) and zero or more spaces. Note the escape in the substitution part is unnecessary: $title =~ s/\s*$/./ is equivelant. In the substitution part, only escape characters that you would escape in a double quoted string - generally. # Assuming the string is clean (i.e. no extra spaces), appending the period is faster than a substituion regex, so I'd use: $string .= '.' to add the period. For checking puctuation you can use the [:punct:] character class $string =~ /[[:punct:]]$/ will detect punctuation at the end of the string, as will: substr( $string, -1 ) =~ /[[:punct:]]/ So any of the following will give you the results you want: unless ( $string =~ /[[:punct:]]$/ ) { $string .= '.'; } unless ( substr( $string, -1 ) =~ /[[:punct:]]/ ) { $string .= '.'; } or their respective abbreviated forms: $string .= '.' unless $string =~ /[[:punct:]]$/; $string .= '.' unless substr( $string, -1 ) =~ /[[:punct:]]/; Hmm, that's probably more than you wanted... -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: OO subclassing, wrong method being called in hierarchy.
Michael Kraus wrote: G'day... I've got three classes in a hierarchy, i.e.: Class A (Super class) | Class B (Subclasses A, Superclasses C) | Class C (Subclass) I have a method (called go) on both B and A. However, if it is called on A die is called as it is designed to be overridden in subclasses of A. When I call go on C, rather than calling go on B, it skips it and calls go on A - causing the application to die. FWIW, I'm also getting Can't locate package A for @A::ISA warnings when using C. Why is this occurring??? If those are the actual package names your using, then you are probably picking up the B package in the core... -- 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 namespace
Ramprasad A Padmanabhan wrote: Is there anyway I can do a using namespace for a particular loop like in c++; ( for functions not exported ) Below are a few dirty little tricks that can get you something similar, but I've never used them, and I'm not sure they are good practice... Use at your own risk! #!/usr/bin/perl use strict; use warnings; use File::Spec (); for my $o ( 'File::Spec' ) { print 'tmpdir: ' . $o-tmpdir(), \n; print 'curdir: ' . $o-rel2abs( $o-curdir() ), \n; } print '#' x 60, \n; do { print 'tmpdir: ' . $_-tmpdir(), \n; print 'curdir: ' . $_-rel2abs( $_-curdir() ), \n; } for 'File::Spec'; print '#' x 60, \n; { local *tmpdir = sub { File::Spec-tmpdir(@_) }; print 'tmpdir: ' . tmpdir(), \n; } print '#' x 60, \n; use import 'File::Spec' = qw( tmpdir rel2abs curdir ); print 'tmpdir: ' . tmpdir(), \n; print 'curdir: ' . rel2abs( curdir() ), \n; __END__ And here is the 'import.pm' module used in the final example above: package import; sub import { my $caller = caller(); my $package = shift; my $module = shift; foreach my $meth ( @_ ) { *{${caller}::${meth}} = sub { $module-$meth( @_ ) }; } } 1; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: search.cpan down :(
Ing. Branislav Gerzo wrote: Harsh Busa [HB], on Sunday, January 23, 2005 at 18:54 (+0530) typed: HB again i m facing issues with connecting to search.cpan.org from india me too, slovakia. Anyone knows something more, why ? This has been going on for a while, affecting everyone. Not sure what is happening. As an alternative, you can use Randy Kobes search engine at: http://cpan.uwinnipeg.ca/htdocs/faqs/cpan-search.html -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Testing the first line of a file
David Gilden wrote: Greetings, I was looking for a way to improve the following: # Check to make sure it is an inTune File open (FH, UPLOAD_DIR . /$file) || error( $q, Error reading $file for test : $! ); while(FH){ if ($_ !~ /\*{5} InTune/){ unlink( UPLOAD_DIR . /$file) or error( $q, Problem deleting file $!); error( $q, The file you uploaded is not an inTune file. Only an inTune export file will be accepted. ); } last; } close FH; It never seemed to work consistently. So after reading through my Perl archive here is what I am now using, which works great! ( special thanks to, Randal L. Schwartz ) # Check to make sure it is an inTune File open (FH, UPLOAD_DIR . /$file) || error( $q, Error reading $file for test : $! ); while (($_ = FH) !~ /[*]{5} InTune/) { unlink( UPLOAD_DIR . /$file) or error( $q, Problem deleting file $!); error( $q, The file you uploaded is not an inTune file. Only an inTune export file will be accepted. ); last; } close FH; The above is wrong. It is not cross-platform safe. Some OS do not allow you to unlink an open file. Always explicitly close files. use File::Spec; my $path = File::Spec-catfile( UPLOAD_DIR, $file ); open( my $fh, $path ) or die $!; my $found_something_objectionable = 0; while (defined( my $line = $fh )) { if ( $line !~ /something/ ) { ++$found_something_objectionable; last; } } close( $fh ); if ( $found_something_objectionable ) { unlink( $path ) or error(...); error(..); } If you only care about the first line, then don't use a loop. Replace it with something like: my $line = $fh; ++$found_something_objectionable if $line =~ /something/; -- 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 ftp/netrc on AIX
Jeff Westman wrote: Hi All, I have an ftp script that connects and does the usual things (change dir., site change mode, transfer file, etc). I am using Net::FTP. Currently, I pass the server name, user id and password from the environment. Is $HOME/.netrc compatible with this module, does anyone know?? When I tried it (basically by added the entry to $HOME/.netrc and commenting out the login lines in my script), it died, basically saying it was not connected. Search the docs of Net::FTP for 'netrc'. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: More elegant solution for a date conversion
Jason Balicki wrote: Hi, I've got a phone record that keeps the date and time in the following format: YYMMDDHHMM example: 0501201500 So, I've written the following to convert it to the format: MM/DD/,HH:MM example: 01/20/2005,15:00 You can use one of the Date modules that understand ISO format, like DateTime. Or you do something like: my $date_str = '0501201500'; my @date = $date_str =~ /\G\d\d/g; my $date_fmt = sprintf( '%s/%s/%s, %s:%s', @date[1,2,0,3,4] ); see `perldoc perlre` `perldoc perlretut` for info on using \G and /g in regexps in array context. see `perldoc -f sprintf` for info on the Csprintf builtin. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: regex needed
Chris Knipe wrote: Lo everyone, Can someone please give me a regex to parse the following... Flags: X - disabled, I - invalid, D - dynamic, J - rejected, C - connect, S - static, r - rip, o - ospf, b - bgp #DST-ADDRESSG GATEWAY DISTANCE INTERFACE 0 S 0.0.0.0/0 r 198.19.0.2 1SERVER-CORE 1 S 196.0.0.0/8r 165.146.192.1 1National Gateway 2 DC 198.19.1.0/24 r 0.0.0.0 0WIRELESS-CORE 3 Ib 198.19.0.0/24 u 0.0.0.0 200 (unknown) 4 DC 198.19.0.0/24 r 0.0.0.0 0SERVER-CORE 5 DC 192.168.1.0/24 r 0.0.0.0 0INTERNAL-CORE 6 DC 165.146.192.1/32 r 0.0.0.0 0National Gateway [EMAIL PROTECTED] I want the regex to return the rule number for all route entries that is static (S Flag) on Interface National Gateway. For added security, I'd like it if the regex will also only return true if the gateway address is part of 165.165.0.0/8 or 165.146.0.0/8 Basically, I need to use the rule number in another command to delete the route entry... So I presume I'll need to extract it via the regex If it's a fixed width data format, its better (easier for you, faster for perl) to break up the string with Csubstr: #!/usr/bin/perl use strict; use warnings; while (defined( my $line = DATA )) { chomp( $line ); my %data; $data{rule} = substr( $line, 0, 2 ); $data{flags} = substr( $line, 3, 2 ); $data{dest_ip} = substr( $line, 6, 18 ); $data{g} = substr( $line, 25, 1 ); $data{gateway} = substr( $line, 27, 16 ); $data{distance} = substr( $line, 43, 8 ); $data{interface} = substr( $line, 52 ); # cleanup, stripping spaces $data{$_} =~ s/^\s+|\s+$//g for keys %data; # reformat or reinterpret data $data{flags} = [ split( //, $data{flags} ) ]; use Data::Dumper; print Dumper( \%data ); } __END__ 0 S 0.0.0.0/0 r 198.19.0.2 1SERVER-CORE 1 S 196.0.0.0/8r 165.146.192.1 1National Gateway 2 DC 198.19.1.0/24 r 0.0.0.0 0WIRELESS-CORE 3 Ib 198.19.0.0/24 u 0.0.0.0 200 (unknown) 4 DC 198.19.0.0/24 r 0.0.0.0 0SERVER-CORE 5 DC 192.168.1.0/24 r 0.0.0.0 0INTERNAL-CORE 6 DC 165.146.192.1/32 r 0.0.0.0 0National Gateway -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: calling Tcl script with ato arguments
Vladimir Lemberg wrote: Hi All, Could you help me to solve following problem: I need to execute tkl script with two arguments (input file and output file) within my Perl script: #!/usr/bin/perl -w use strict; use File::Basename; my @gdflist = `find . -name *.gdf`; my $gdf_number = scalar(@gdflist); my $counter = 0; foreach my $gdf (@gdflist){ my $base = basename $gdf; my $path = dirname $gdf; $base =~ s/(.*)(\.)/$1$2/; chomp($gdf); my $arg1 = $gdf; my $arg2 = $path/$1_patched.gdf; system patch_teleatlas_gdf.tcl $arg1 $arg2 or die patch_teleatlas_gdf.tcl is not working properly; $counter ++; print \{$gdf\}:PATCHED($counter of $gdf_number); } The problem that I'm receiving the die message patch_teleatlas_gdf.tcl is not working properly but then I manually assign arguments, Tcl script works with no problem. my arg1 = ./CSK/cansk47.gdf; my arg2 = ./CSK/cansk47_patched.gdf; system patch_teleatlas_gdf.tcl $arg1 $arg2 or die patch_teleatlas_gdf.tcl is not working properly; Any ideas? Should i use execvp(3) instead? Csystem returns the exit code of the program executed. Most programs return 0 (zero) on success. However, zero is treated as a false value in perl, so your Cor condition above is executed when the tcl script succeeds. You need to compare the result of system to zero to determine success: system(...) == 0 or die; A more perlish version of your script might look like (untested): #!/usr/bin/perl use strict; use warnings; use File::Find; use File::Spec; my $script = 'tickle.tcl'; my $count = 0; find( sub { return unless /\.gdf/ -f; (my $base = $_) =~ s/\.[^.]+$//; my $src = $File::Find::name; my $dest = File::Spec-catfile( $File::Find::dir, ${base}_patched.gdf ); system( $script, $src, $dest ) == 0 or die error code $? returned: $!; ++$count; }, 'downloads' ); print $count files patched\n; __END__ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Extracting links.
Sara wrote: I am trying to extract links along with HTML tags a href=blah from a list, but it's not working on my XP machine with Active State Perl 5.0.6 Kindly help. # CODE START my @array = qq| bodya href=http://www.mydomain.com;img alt=Free Hosting, Freebies border=0 src=http://www.mydomain.com/images/logo2.gif;/a |; #extract LINKS (no image links) only a href=http://www.mydomain.com; my @get = grep {/a .*?/} @array; print @get\n ### CODE END ### I'm not sure why you're assigning a string to an array... (completely untested) my $html = HTML; bodya href=http://www.mydomain.com;img alt=Free Hosting, Freebies border=0 src=http://www.mydomain.com/images/logo2.gif;/a HTML use HTML::LinkExtractor; my $lx = new HTML::LinkExtractor(); $lx-parse(\$html); for my $link( @{$lx-links} ) { if( $$link{tag} !~ /img/i ) { my $href = $$link{href}; print $href-as_string(); } } __END__ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Use Strict
Graeme St. Clair wrote: In accordance with The Rules, I added use strict use warnings to a script invoked from a browser page on the same machine. Last time I did this, as soon as I used the browser page, Apache 'error.log' promptly showed scads of msgs along the lines of '[Wed Dec 08 11:03:52 2004] [error] [client ###.###.###.###] Global symbol $dbh requires explicit package name at c:\PROGRA~1\...\###.pl line 358.' This time, all that happened was that the browser (IE, alas) walloped off into a loop (maybe) and nothing new ever came up in the new frame, although there did seem to be disk activity. I eventually elicited a list of error msgs by just flat out compiling the thing from the Windows cmd line, but is there something more intelligent I could have done to force out some diagnostics on the Apache log? use CGI::Carp qw( fatalsToBrowser ); See `perldoc CGI::Carp` -- 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 with extracting line
Anish Kumar K. wrote: Hi I have text file in which I have the below mentioned lines This is a test start-first First Line testing end-first How are you Finally start-second Tested end-second I have a perl file which reads the above file and stores in the variable say $message #!/usr/bin/perl use strict; open INPUT,fp.txt || die File does not exist; my $message=; while(INPUT) { $message=$message.$_; } if ($message =~ (/start_first/../end_first/)) { print The line is $1; } What I expect is that from the variable, $message I wanted to print out this First Line testing as in the text file i have specified the pointers.. In Short I wanted to print the lines in between two words in a file/variable. Below is an example of how the .. operator works. You can find a good description in `perldoc perlop` section Range Operators #!/usr/bin/perl use strict; use warnings; while (defined( my $line = DATA )) { if ( $line =~ /start-/ .. $line =~ /end-/ ) { print The line is $line; } } __DATA__ This is a test start-first First Line testing end-first How are you Finally start-second Tested end-second # Note that the loop above can and often is abbreviated: while (DATA ) { if ( /start-/ .. /end-/ ) { print The line 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: strict and warnings
Dave Kettmann wrote: Hello all, I have seen in quite a few posts to the list from the non-beginners, who I think all of us beginners appreciate them taking their time to help us true beginners, make some references to the strict and warnings pragmas. So I have a question about them. Some of the time I see them say that the pragmas are good for developing programs/scripts. The way it is worded some times it seems as if after the program is written and in 'production' to take these lines out of the code. Do they slow down how perl processes the programs? Does it hurt to leave them in? Just a question from a beginner who is trying to progress along the wonderful road of Perl :) In just about all the code I write, I use strict warnings (in every package). The exeception is in Module::Build and some of its ancillary modules where we don't use warnings because we try to remain backwards compatable to at least 5.005 and warnings only appeared in 5.006. However, there is some baggage in using warnings, and some people do remove it from production code. If you're really concerned, I'd suggest benchmarking. If after benchmarking you notice a significant change, you can try something like: use if $ENV{UNDER_CONSTRUCTION}, strict; use if $ENV{UNDER_CONSTRUCTION}, warnings; or even: BEGIN { if ( $ENV{UNDER_CONSTRUCTION} ) { for my $m ( qw( strict warnings ) ) { require $m.pm; $m-import; } } } But, I don't really worry about it. I've never used anything like that in my code. If there are speed problems, there are usually better candidates for optimization. I have never had to remove, or even think about removing, either pragma for speed considerations. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: strict and warnings
JupiterHost.Net wrote: Chris Devers wrote: On Thu, 13 Jan 2005, Dave Kettmann wrote: [...] Some of the time I see them say that the [strict / warnings] pragmas are good for developing programs/scripts. The way it is worded some times it seems as if after the program is written and in 'production' to take these lines out of the code. Do they slow down how perl processes the programs? Does it hurt to leave them in? No, leave them in, always. Yep! There should be little if any noticable speed difference. Also 100% correct: I did a benchmark of use strict; use warnings; print 1; vs. print 1; Benchmark: timing 1000 iterations of no pragma, w/ pragma... no pragma: 4.9282 wallclock secs ( 4.79 usr + 0.01 sys = 4.80 CPU) @ 208.33/s (n=1000) w/ pragma: 4.97848 wallclock secs ( 4.95 usr + -0.01 sys = 4.94 CPU) @ 2024291.50/s (n=1000) Rate w/ pragma no pragma w/ pragma 2024291/s-- -3% no pragma 208/s3%-- So it costs 3% more every ten million times it runs, the benefits of leaving it in are much more valuabel than 3%/1000 :) Actually, what happens is that importing those pragma cause flags to be set (eg $^H, see `perldoc perlvar`). Perl checks these flags during certain operations. If the flags are set then perl will do extra checking in the case of strict.pm and also emit warnings in the case of warnings.pm, so your benchmark doesn't really measure the cost. You'd have to benchmark on a project by project basis. Not that I'm trying persuade anyone against using them. As I said, I pretty much always use them. Any needed optimizations can usually be found elsewhere. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Image Creation: labels
Daniel Kasak wrote: Hi all. I'm hunting for a method of creating labels under Linux. I've already looked at everything on freshmeat.net that came up when I searched for 'labels'. None of them cut it. Requirements: - Coloured, rotated ( 90 degrees ) text rendering - Coloured rectangle rendering That's it. You'd think one of the existing labelling packages would accomodate me so far, right? Nope. Background: We have a filing system where each file has a label, which is made up of ( mainly ) coloured numbers ( ie each number gets a different colour *background* ). This last bit ... the coloured background ... is what's stopping me from using any of the existing labelling packages. So now that I've decided that there isn't anything out there that does what I want, I'm going to have to write something. What should I use? I've had a brief look at PDF::API2, but I can't even figure out if it does what I want - the documentation is a little nonexistant. So should I use GD? http://search.cpan.org/dist/PostScript-MailLabels/ or use some of the PostScript::* modules to roll your own. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Circular References, Self Referenced memory ang Garbage Collection
Marcos Rebelo wrote: Some time ago I read one article about this Consider that you have: { # make $a point to itself my $a; $a = \$a; } Or { # make $a and $b point to each other my ($a, $b); $a = \$b; $b = \$a; } This memory will be free just at the end of the process. This can became a problem. If I'm not wrong there is a subroutine that makes a reference as a weak referenc but how? perldoc Scalar::Util weaken() isweak() -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: installing perl
Octavian Rasnita wrote: Hi, I have tried to install DBI and I saw that it tells me that perl is installed thread enabled and that this is not recommended for production environments. How can I install perl without beeing thread enabled? I use perl 5.8.4 under Linux Fedora Core 2. If Fedora offers a non-threaded perl, just intall it the regular way. Otherwise you'll need to download[1] and compile the source, which is a good exercise anyway. Be sure to read /all/ the docs[2][3][4]. If perl is already installed, can I do something to make it not beeing thread enabled without re-installing all the modules? If you switch to a non-threaded perl from a threaded perl, you will need to recompile any XS modules. 1. http://search.cpan.org/dist/perl/ 2. http://search.cpan.org/src/NWCLARK/perl-5.8.6/README 3. http://search.cpan.org/dist/perl/INSTALL 4. If non-unix see the appropriate README.* Scroll down to the Documentation section at http://search.cpan.org/dist/perl/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $@ not working
Siegfried Heintze wrote: I have the following code (extracted from my cgi program) and I am expecting it to display an error message when it hits the if ($@){...} as a result of hitting the die statement. It does not (as indicated by single stepping with the windows perl debugger)! Instead it takes the else! Why? Did you try the code snippet below as posted? It runs as expected here. I'm using ActiveSTate 5.8+. I tried perldoc.bat -f die but did not find any clues to my problem. eval{ die No valid ID for User; }; if($@){ However, you probably want to save the error: if ( my $err = $@ ) { print start_html(-title = Error: $case_name, -onload = BodyLoad();, -style = {src=../../css/convex.css} ), p(h1 Error: $@); And change this to: p(h1 Error: $err); because $@ has been reset by the time you get here. print concat( [EMAIL PROTECTED]); } else { } Thanks, Siegfried Randy. -- 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 problem about warning information.
Perl Hacker wrote: Below is my script, When I run the script, everything is ok. #! /usr/bin/perl w print 111\n; warn 222 \n; Problem emerges when using the following command line under csh, $test.pl test.log Where test.log is like: 222 111 However, what I experted is: 111 222 Do you guys have any idea about that? Thanks a lot. Cprint goes to stdout which is buffered for efficiency, while Cwarn and Cdie go to stderr which is not buffered so that errors are displayed immediately. You should be able to see it on any terminal with print '1'; warn '2'; (the newlines sometimes force flushing of the buffer) You can unbuffer stdout with: $| = 1; print '1'; warn '2'; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: $@ not working
Siegfried Heintze wrote: Does this qualify as a simplified version of the code snippet below? eval{ print begin\n; die throw; print done main\n; }; if(my $err=$@){ print Exception = $err\n; } else { print No exception\n; } When I single step thru this with the Open Perl IDE debugger on ActiveState Perl 5.8+, it prints No Exception. I'm expecting it to print Exception = throw. Is there a bug in my program, a bug in perl, or a bug in me? What happens outside of the debugger? -- 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
Sandy Santra wrote: Hi, this is just a test. I've been having a lot of problems posting to this list, as I keep getting the following message (even though I'm sending a text message): [EMAIL PROTECTED]: ezmlm-reject: fatal: Sorry, I don't accept messages of MIME Content-Type 'text/html' (#5.2.3) This is correct. Please do not send HTML formatted messages to the list. Your mail application should provide an option to send plain text. You should always send plain text; HTML messages can be too easily misused for malicious purposes, not all mail readers understand HTML foramatted messages, etc. That is why it is considered bad etiquete and disallowed by most sensible list admins. It's also why I have filters set on my personal inboxes to send Content-Type: text/html (and most Content-Type: multipart) straight to the junk folder. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: h2xs directory structure in perl-5.8.x?
Alex Daniloff wrote: Hello Perl people, Recently, upgrading to perl v5.8.5 I've noticed that h2xs lays out module directory structure in a quite different way than before. Prior to this I could create a module e.g. Data::Loader h2xs -XA -n Data::Loader And it would create directory Data, then subdirectory Loader with Loader.pm module and other files. The full path to the module looks like /Data/Loader/Loader.pm If I want to create another module e.g. Data::Reader h2xs would put it into /Data/Reader/Reader.pm Which is logically correct. How the same command produces directory Data-Loader with service files and subdirectory lib in which it creates subdirectory Data in which it creates the module Loader.pm The full path to the module looks like /Data-Loader/lib/Data/Loader.pm For another module e.g. Data::Reader it will be /Data-Reader/lib/Data/Reader.pm Why? Makes no sense to me. What the hell is going on with h2xs? Thank you in advance for any clues or practical help. That behaviour was changed to reflect current conventions for directory layout. If you look at other modules that perform the same function, Module::Starter[1] ExtUtils::ModuleMaker[2], you'll see that they behave the same way. 1. http://search.cpan.org/dist/Module-Starter/ 2. http://search.cpan.org/dist/ExtUtils-ModuleMaker/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Patches
Octavian Rasnita wrote: Hi all, Does anyone know if there are perl modules for applying patches? I have seen on many lists that are provided some patches for some perl modules, and probably they can be applied automaticly under Unix using patch for .dif files, but I cannot do this under Windows. So, are there any perl modules that can do this job under Windows? (Because otherwise I have to do it manually and it is not very easy). You can get a port of patch and diffutils from from the GnuWin32 project[1]. There is also WinMerge[2]. 1. http://gnuwin32.sourceforge.net/ 2. http://winmerge.sourceforge.net/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Hash problem
Mike Blezien wrote: Hello, I'm working on settup a hash something like this: my $catid = 'A'; my(%conf); $conf{cat} = { A = ( [15.00,Three months(90days),90], [30.00,Six months(180 days),180], [45.00,Nine months(270 days),270], [60.00,Twelve months(365 days),365] ), B = ( [20.00,Three months(90days),90], [40.00,Six months(180 days),180], [50.00,Nine months(270 days),270], [70.00,Twelve months(365 days),365] ) }; print header(); for (my $i=0; $i@{$conf{cat}-{$catid}}; $i++) { print qq~CatPrice: $conf{cat}-{$catid}[0] CatDays: $conf{cat}-{$catid}[2]BR~; } But all I'm getting is the first element array in key 'A' 15.00 90 instead of all 4 array in the key in the loop... what I'm I doing wrong, or is there away doing this better ?? Your data is not structured as you may think it is. Try printing it out with Data::Dumper. use Data::Dumper; warn Dumper( \%conf ), \n; More specifically, elements of a hash or array must be a scalar not a list. Hash elements 'A' 'B' in your code above cannot be a list of array references, they should probably be array references: $conf{cat} = { A = [ ... ], B = [ ... ], }; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: having problem finding the correct regexp using with split()
[EMAIL PROTECTED] wrote: Hi all, again i am sending a message to this list hoping you bear with me and my novice question. In my script i would like to split a single scalar containing a random passage of text into a list, which holds the words of the text. What i found in the perl documentation is the following example [perlrequick - The split operator]: #For example, to split a string into words, use # # $x = Calvin and Hobbes; # @word = split /\s+/, $x; # $word[0] = 'Calvin' # $word[1] = 'and' # $word[2] = 'Hobbes' For my case however i would like to have also linefeeds treated as words, because i want to preserve them (in order not to mix up the layout of the text when writing the list of words to an outfile). Consequently i would think that using like in the example above #!/usr/bin/perl use strict; use warnings; my $all_of_it = EOF; Word a_linefeed_follows_now Word EOF # my @word = grep length, split( /(\n)|\s+/, $all_of_it ); # -or- # my @word = grep $_ =~ /\n|\S+/, split( /(\s+)/, $all_of_it ); foreach (@word) { print This element is: , ( $_ eq \n ? '\\n' : $_ ), \n; } -- 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 problems
Ken Gillett wrote: I've been running RH 8 on my server for some time and regularly ran a fairly complex perl script that parsed an XML file and contained the following line:- last if /^\t{0,2}$tag$/; which would exit the loop at the end of that 'section' as $tag in fact contained /dict. On upgrading to RH 9 this all fell apart and I spent the best part of a day trying to find out why and where it was failing. Strangely, it WOULD work if I replaced $tag with the literal string it contained (i.e. /dict) or when it found the line beginning with a single tab (i.e. way further down the file), but would NEVER recognise 2 tabs and using $tag. On investigation I discovered that the above works perfectly with RH 8's Perl 5.8.0.55 (and my Mac's 5.8.1), but NOT with RH 9's 5.8.0.88. I upgraded to 5.8.5 and all's well again:-) Is this a known problem with that version of Perl or as usual am I the first to discover a bug in such a widely used piece of software? You'd have to check with the RedHat folks to see the changelog between their releases 55 and 88, to see what chages they applied. It was probably a unicode bug. The first couple of releases in the 5.8 series were kinda buggy in that area; I've only recently began to switch over completely to 5.8. If you're using a 5.8 series perl for production, I'd recomend a later release that 5.8.0 or 5.8.1 Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: If you´re in the mood, help me.
[EMAIL PROTECTED] wrote: Hi guys, As you know, i´m having some problems to make this thing work. I have to write a script that automatically sends a code and get the some information according to that code. I mean, this script has to automatically fill in a formfield and get the result. But I just can´t get it done. If you´re really really in the mood for helping me, I´m posting down here the source code of the page of the form that the script must fill in and get the result. The url is: http://www.tj.go.gov.br/online/Inicial/Processos/ConsultaProc_1Grau_Capital.dml And here is the URL for the page that returns the result: http://www.tj.go.gov.br/online/Capital/Processos_SPG/Resp_Processo1.dml Take a look at the WWW::Mechanize module: http://search.cpan.org/dist/WWW-Mechanize/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Printing ?
Paul Ohashi wrote: Hi All, Is there a way to 'print' to STDOUT and a FILE with one line? Something like:echo Some text | tee - a somefile.out http://search.cpan.org/dist/IO-Tee/ -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: confusing warnings and void values
RichT wrote: Hi all, its time again for me to hassle you, i have my script mostly working, but iv have been bashing my head against a wall trying to fix the last bits... its a script for extracting data from a file and exporting it to another. Problems: 1) i keep getting the warning Use of uninitialized value in numeric eq (==) at ./scanDCI.pl line 122, DCIFILE line 28. but it should never execute ./scanDCI.pl line 122 for DCIFILE line 28. as thats the DE line... initialize C$inElementSection: my $inElementSection = 0; 2) i get void as the 3rd value in the output [shelf-1-slot-12-port-1,15552,void,] but that should be the same as the 2nd value in this case. The variable C%segmentFields should be an array since it is being used as an array. This was fixed when I made that change. Also, note that in all cases found in your code, you should be using Cmy instead of Cour. #!/bin/perl use strict; use warnings; use Getopt::Long; Getopt::Long::config qw(no_ignore_case); my ( $inputFile, $outputAllFields, $searchKey, $outputFields ); my @foundSegments; { $outputFields = 'name,deviceSpeedIn,deviceSpeedOut'; my $needHelp; GetOptions( 'dciInFile=s' = \$inputFile, 'findField=s' = \$searchKey, 'showFields=s' = \$outputFields, 'listAllFields' = \$outputAllFields, 'help|h|H|?|HELP' = \$needHelp ); die usage() if $needHelp; } # Data collection # using an input file # else quit if ($inputFile) { findVars($inputFile); } else { die usage(); } # Data output #if request for keys print all keys #else print results if ($outputAllFields) { foreach ( @foundSegments ) { foreach (keys %$_) { print $_, ; } print \n; } } else { foreach my $found (@foundSegments) { foreach my $showKey (split /,/, $outputFields) { print $found-{$showKey},; } print \n; } } sub usage { return USAGETEXT; usage: $0 -dciInFile filename -dciInFile filename is the dci file you want to scan the following options are also availble [ -findField fieldName ]this is the search key to be used (by default all elements will be returned) [ -showFields field names ] feilds to output (default is name,deviceSpeedIn,deviceSpeedOut) [ -listAllFields ] list avalible fields [ -help]this help text USAGETEXT } sub findVars { # find infomation form Concord's dci files # usage: # findVars(key to search in,value to search for) # # output: # an aray of Hashes containing all matched segments and keys my ($dciFile, %segment, @segmentFields); my $inElementSection = 0; # read in dci filename from parent $dciFile=$_[0] || die qq( FindVars function: Missing dciInfile value $!); chomp $dciFile; open(DCIFILE, $dciFile) || die FindVars function: can not open : $!; foreach my $line (DCIFILE) { chomp $line; if ( $line =~ /^FN,Elements,/ ) { $line =~ s/FN\,Elements\,//g; @segmentFields = split(/\,/,$line); next; } if ( $line =~ /^DS,,Elements,/ ) { $inElementSection=1; next; }#marks start of elements if ( $line =~ /^DE/ ) { $inElementSection=0; next; }#marks end of elements if ($inElementSection==1) { my @segmentValues = split(/\,/,$line); for ( my $i = 0; $i $#segmentValues; $i++ ) { $segment{$segmentFields[$i]} = $segmentValues[$i]; } push @foundSegments, \%segment; next; } } close DCIFILE; return (@foundSegments); # return to main ruteen } -- 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 on structure definition
Ing. Branislav Gerzo wrote: Hi! I am thinking about best hash structure, I want save all datas from hash to database. Example: Explanation: elements in 'ra' are always 1 times in hash, elements in 'ro' should be zero or more times. Do you think this is good way how to declare hash ? It depends a lot on how you are using it, but... In 'ro', is there a particular reason your using numbers 1, 2, ... as keys? If there is not, I'd use an array. Something like: 'name' = { 'ra' = { 'do' = undef, 'od' = '1996-01-07', 'name' = 'brano' }, 'ro' = [ # an array of hashes { # this was {name}{ro}{1}, now it's {name}{ro}[0] 'do' = undef, 'od' = '1998-01-01', 'name' = 'john' }, { 'do' = '1991-05-15', 'od' = '1992-11-01', 'name' = 'michael' } ] } -- 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 with strings
[EMAIL PROTECTED] wrote: Hi Frnds, I have a problem with string passed as an argument to a perl script. I am giving the string \C:\\PROGRA~1\\INTERN~1\\IEXPLORE.EXE\ as an argument to the cmdtemplate option. and it been taken as C:PROGRA~1INTERN~1IEXPLORE.EXE after parsing it. what happend to the back slash.?? I'm not on my Windows box atm, but are you saying that you're giving the string: \C:\\PROGRA~1\\INTERN~1\\IEXPLORE.EXE\ as a command line argument to your program? eg your-program \C:\\PROGRA~1\\INTERN~1\\IEXPLORE.EXE\ Escaping should not be neccessary, just use: your-program C:\PROGRA~1\INTERN~1\IEXPLORE.EXE -or- your-program C:\PROGRA~1\INTERN~1\IEXPLORE.EXE -or- your-program C:\Program Files\Internet Explorer\IEXPLORE.EXE (there are a couple of other wierder variations on the above, but they shouldn't be mentioned in public. =) All of which are legal, and all of which should pass corectly into your program. Randy. -- 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::Tree help
Ing. Branislav Gerzo wrote: Hi all, I have to parse some thousand of html files, so I'd like to use some html parser, and not my own regexpes. Htmls I am parsing are quite complex, so I need your help. First of all, is HTML::Tree good and fast module? Because, I am not sure if I have to look for some criteria using if( my $h = $tree-look_down('_tag', 'sometag') ) { } it is not slow ? When I used Dumped through Data::Dumper, from 300 kb html file is 13mb dump output... There are basically two types of parser: 1) the type that reads in html, xml, etc. and builds an in memory representation of the data, usually a hierarchical tree structure, and 2) the type that reads in the file and fires off events for each of the tags/elements it encounters. The first type is very convenient, especially when you want to reference lots of random elements from the data, but it takes up a lot of memory and is usually slower. HTML::Tree is of this type. The second type is fast and only takes up as much memory as you allow because as each element is encountered you decide whether to hang on to the data or throw it away. HTML::Parser is of this type. Having said all that, I did a quick search on the CPAN: http://search.cpan.org/search?query=html%20tablemode=all and near the top I see two modules that migh help you out. They are both based on HTML::Parser and they both deal exclusively with html tables: HTML::TableExtractor HTML::TableContentParser I haven't used either of these, but a quick look at the docs seems to indicate that HTML::TableExtractor works a lot like HTML::Parser: as it encounters tables and table elements it fires off events so that you can process the date. HTML::TableContentParser seems to work like HTML::Tree: it reads the data and constructs a simple structure that holds the tables found in the document. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Error: Scalar found where operator expected
vishwas bhakit wrote: hello, I had used following line in my code to retrieve message where $msg_id shows id of message retrieved by LIST command. code: my $message=$pop3-RETR $msg_id; # Line No. 30 it is showing me following error Error: Scalar found where operator expected at try.pl line 30, near -RETR $msg_id (Missing operator before $msg_id?) syntax error at try.pl line 30, near -RETR $msg_id Execution of try.pl aborted due to compilation errors. I am not getting what is the cause of this error . Can anybody plz tell me what is the cause of this. from `perldoc perldiag` %s found where operator expected (S syntax) The Perl lexer knows whether to expect a term or an operator. If it sees what it knows to be a term when it was expecting to see an operator, it gives you this warning. Usually it indicates that an operator or delimiter was omitted, such as a semicolon. What is $pop3? What is RETR? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: tie variable to function?
JupiterHost.Net wrote: Hello list, I saw this recently on here but can't find the thread and since I'm not sure what the technique is called (tie variable to function?) I'm not sure where to look on perldoc :) What is it called/How do you go about doing it when you have a var that each time is used (IE printed or in calculation) has the current value of a function? perldoc perltie perldoc Tie::Scalar package Tie::Time; use strict; use warnings; require Tie::Scalar; our @ISA = ( 'Tie::StdScalar' ); use Carp; sub STORE { croak Can't change time.\n } sub FETCH { return time() } package main; use strict; use warnings; tie( my $time, 'Tie::Time' ); print $time\n; sleep( 5 ); print $time\n; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Blocks in Perl
Michael Kraus wrote: G'day... I know when say reading a file handle or performing a database update that if the function fails you can use one of the or operators to execute an aleternate statement (either or per say or ||). What happens if you want to execute more than one statement? E.g. $sth-exectute(1, $str) || { $obj-addError(DB write failed); return undef; } I'm guessing the above isn't legal, maybe I could use something like: $sth-execute(1, $str) || ($obj-addError(DB write failed) return undef); The clearest way is to use a gool 'ole fashioned conditional: unless ($sth-execute( 1, $str )) { ($obj-addError(DB write failed); return undef; } Very straight forward. Very easy to read. And, IMO, The Right Way to do it. But if you ever /do/ find yourself in need of grouping statements together you can use a Cdo statemnt (`perldoc -f do`). $sth-execute(1, $str) || do { ($obj-addError(DB write failed); return undef; } Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sorting with Swartz Transform
Jeremy Kister wrote: I am trying to simplify some of my code. The output I am expecting is: 1 17.0.0.1 5 27.0.0.1 5 127.0.0.1 5 209.0.0.1 6 10.0.0.1 10 127.0.1.1 where the first colomn is the main sorting column, and if there are multiples of that value, the ip should be sorted. I have code the performs the task, but it's a Swartzian Transform, a temporary array, another swartz transform, and just feels icky. any suggestions to pretty this bloat ? #!/usr/local/bin/perl $hash{'127.0.0.1'} = 5; $hash{'127.0.1.1'} = 10; $hash{'27.0.0.1'} = 5; $hash{'10.0.0.1'} = 6; $hash{'17.0.0.1'} = 1; $hash{'209.0.0.1'} = 5; my @ipsorted = map { $_-[0] } sort { $a-[1] = $b-[1] } map { [$_,split /\./] } keys %hash; foreach my $ip (@ipsorted){ push @unsorted, $hash{$ip} $ip; } foreach my $sorted (map { $_-[0] } sort { $a-[1] = $b-[1] } map { [$_,split] } @unsorted){ print $sorted\n; } Beware the costs of Cmap, Cgrep, and the like. They are sometimes very handy, but remember that each one represents an iteration through the entire list. In your above example, there are at least 8 (possibly 9?) iterations through the list: 4 map operations, 2 sorts, 2 explicit loops, and 1 keys op. In addition to the cost in speed of the multiple iterations, there is also an unseen temporary list created to hold the results of each of those Cmap, Csort, and keys operations. I'm not sure how long the temporaries are held, but there has to be atleast 3 copies present in memory for each of operations in the Swartz Transform: 1) the original, 2) the list being iterated over, ie the right-hand side argument, and 3) the result list being created. That's a pretty big cost in speed and size. For your example, you're probably better off writing one explicit loop which takes the data in %hash and places it into a more appropriate data structure. After it's in a more appropriate structure you can sort it. (That's 2, maybe three iterations, and 1 temporary... I think). Randy. -- 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 question about the return value of a subroutine
Zeng Nan wrote: Hi, Here is a simple program: 1 my @nums = (1..100); 2 my $result = total(@nums); 3 4 print $result\n; 5 6 sub total { 7 my $sum; 8 foreach(@_){ $sum += $_ } 9 $sum; 10 } My question is without line 9, the return value is nothing, while I expect it will return the value of $sum, as it is the last expression being evaluated, is it correct? Actually, Cforeach is the last statement in your routine, and it has no meaningful value. Note also that the variation: sub sum { my $sum = 0; $sum += $_ for @_; } does not work either though I think it probably should. Regardless, I think it is good practice to always return explicitly with a Creturn statement. It makes the code clearer and easier to read. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: converting the elements of a hash to uppercase
John W. Krahn wrote: Octavian Rasnita wrote: Hi all, Hello, Please tell me how to convert the elements of a hash to uppercase, if I can access that hash only by reference. For example, I have something like: my $ref = { 'a' = 'aaa', 'b' = 'bbb', 'c' = 'ccc' }; And I want to make 'a' to be 'A', 'b' to be 'B' and so on, but the values of the hash need to remain the same. I have tried using map() but without success. Did you try it like this: %$ref = map { uc, $ref-{ $_ } } keys %$ref; Be carefull of constructs like these; they often turn out to be inefficient and slow. It's actually equivelant to something like: my $ref = { 'a' = 'aaa', 'b' = 'bbb', 'c' = 'ccc' }; my %tmp; while ( my( $k, $v ) = each %$ref ) { $tmp{uc($k)} = $v; } $ref = \%tmp; Here is a comparison: #!/usr/bin/perl use strict; use warnings; sub a_map { my $ref = { 'a' = 'aaa', 'b' = 'bbb', 'c' = 'ccc' }; %$ref = map { uc, $ref-{ $_ } } keys %$ref; } sub b_expanded { my $ref = { 'a' = 'aaa', 'b' = 'bbb', 'c' = 'ccc' }; my %tmp; while ( my( $k, $v ) = each %$ref ) { $tmp{uc($k)} = $v; } $ref = \%tmp; } sub c_inplace { my $ref = { 'a' = 'aaa', 'b' = 'bbb', 'c' = 'ccc' }; foreach my $k ( keys %$ref ) { $ref-{uc($k)} = delete( $ref-{$k} ); } } use Benchmark qw(cmpthese); cmpthese( 0, { 'map' = \a_map, 'expanded map' = \b_expanded, 'inplace' = \c_inplace } ); __END__ Benchmark: running expanded map, inplace, map, each for at least 3 CPU seconds.. . expanded map: 5 wallclock secs ( 3.53 usr + 0.00 sys = 3.53 CPU) @ 10844.87/s (n=38239) inplace: 5 wallclock secs ( 3.13 usr + 0.00 sys = 3.13 CPU) @ 11818.12/s (n=37038) map: 3 wallclock secs ( 3.06 usr + 0.00 sys = 3.06 CPU) @ 9780.03/s (n=29966) Rate map expanded map inplace map 9780/s -- -10% -17% expanded map 10845/s 11% -- -8% inplace 11818/s 21% 9% -- -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: converting the elements of a hash to uppercase
Octavian Rasnita wrote: Hi all, Please tell me how to convert the elements of a hash to uppercase, if I can access that hash only by reference. For example, I have something like: my $ref = { 'a' = 'aaa', 'b' = 'bbb', 'c' = 'ccc' }; And I want to make 'a' to be 'A', 'b' to be 'B' and so on, but the values of the hash need to remain the same. I have tried using map() but without success. You can't modify the key; you can only create a new one and remove the old one: #!/usr/bin/perl; use strict; use warnings; my $ref = { 'a' = 'aaa', 'b' = 'bbb', 'c' = 'ccc' }; while ( my($k,$v) = each %$ref ) { $ref-{uc($k)} = delete( $ref-{$k} ); } use Data::Dumper; print Dumper( $ref ); __END__ -- 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 get text after comment
[EMAIL PROTECTED] wrote: Hi, I need to capture whole text after # character in each line from a file.The below script is not working can any one suggest the correct thing plz.. Your regexp: if ($line1 =~ /^#\(.*\)/) matches any string that: begins with '#' followed by a literal '(' followed by zero or more of any character followed by a literal ')' From your description above, you want something like: /#(.*)$/ which captures anything following a '#' up to the end of the string. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: TCL
Chris Devers wrote: On Mon, 8 Nov 2004, Custard, Carol N. wrote: Does anyone know tcl? Yes. I'm sure someone does. What specifically are you wanting to know? And how is it related to Perl? ;-) -- 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 $. line number special variable
Joseph Paish wrote: how do you use the line number variable inside a while loop like i am trying to do below? i never get to process the first line of the file, and as a result, subsequent calculations are inaccurate. it always jumps to the second if statement. Like the others, I don't see any problems in the posted code other than maybe some stylistic differences. Here is how I would probably write it: #!/usr/bin/perl use strict; use warnings; use constant FILE = 'data'; open(my $fh, FILE ) or die (Can't open @{[FILE]}: $!) ; while (defined( my $line = $fh )) { chomp( $line ); if ( $. == 1 ) { # first line is initial values # process intial values here print HEADER: $line\n\n; } else { #process subsequent values here print $line\n; } } # end of while loop close( $fh ) ; __END__ Alternatively, you can use the range operator, which may be more idiomatic, in the condition: if ( 1 .. 1 ) { -or- unless ( 2 .. eof() ) { See `perldoc perlop` - Range operator Also, you may want to review the entire section in `perldoc perlvar` on the $. variable. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: cpaninstall NET::SSH ---- Can't install NET::SSH don't know what it is?
On 11/7/2004 8:35 AM, Harold Castro wrote: Good day! This is the first time I'll be using the cpan to install modules. I run: perl -MCPAN -e shell and answer the questions one by one. When its done, I issued install NET::SSH at the cpan prompt and I got the message: cpan install Net::SSH case matters -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Parsing strings like the Windows shell
[Fwd: Re: [Module::Build] ANNOUNCE: 0.2601 - CPAN] Please forgive my lack or proper etiquette, but I want have access to a Windows machine for a few days, and I want to try to resolve this issue. For the Module::Build project we need to be able to parse strings like the command shell. I'm not sure of all details of how the shell interprets commands, but I think the algorithm below is close. Can anyone verify this and maybe help provide a routine that implements it. I'll make sure you're credited for the contribution. =) Thanks, Randy. Original Message Subject: Re: [Module::Build] ANNOUNCE: 0.2601 - CPAN Date: Sun, 07 Nov 2004 14:17:14 -0500 From: Randy W. Sims [EMAIL PROTECTED] Reply-To: [EMAIL PROTECTED] To: Ken Williams [EMAIL PROTECTED] CC: [EMAIL PROTECTED], [EMAIL PROTECTED], Perl - Module-Build [EMAIL PROTECTED] References: [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] [EMAIL PROTECTED] Ken Williams wrote: On Nov 7, 2004, at 11:32 AM, Randy W. Sims wrote: If necessary we can either try to emulate it be experimenting or maybe we can dig some code out of ReactOS (a Windows NT clone) and FreeDOS (a DOS clone) and translate it to perl. Okay - I'm happy with just a subset of it for now. Let's do what we can with 2-3 lines of regexes and such in Windows-split_like_shell(), and wait until we get some legitimate complaints. I think we've already fixed the most common problems. Actually, I think I just stumbled across the algorithm. After sending my previous message, I was looking at the results from the brief experiments I posted [see sig], and I think I found an algorithm that works for those cases. But I'm not by a Windows box to test at the moment. Scanning the string char by char: Quote mode is alternately entered and exited upon find a d-quote unless the d-quote is preceeded with a b-slash or unless the d-quote is preceeded with a d-quote that terminates quote-mode in both cases the d-quote is a literal part of the argument. Given the previous used example: foo\bar foo\bar discard and enter quote-mode f shift o shift o shift discard and exit quote-mode \ literal unless next char is d-quote escaped d-quote, discard b-slash, shift d-quote b shift a shift r shift discard and enter quote-mode quoted space discard and exit quote-mode f shift o shift o shift \ literal unless next char is d-quote escaped d-quote, discard b-slash, shift d-quote b shift a shift r shift discard and enter quote-mode Correctly produces the result: foobar foobar Open questions: Does b-slash escape any other characters? spaces? Does all versions follow this basic algorithm? NT has circumflex as an additional escape char, we probably don't care. Anybody by a Windoze box to try this out? If not, I'll try in a few days when I get a chance. Randy. __END__ -- #!/usr/bin/perl use strict; use warnings; print $_\n for @ARGV; __END__ and I got the same results. I'm not quite sure how that line is being interpreted. What I do know about the cmd.exe shell is that: 1. circumflex is the escape character 2. you can get a quote inside a quoted string by repeating it x3, i.e. foobar = foobar foobar = foobar experimenting (w/ echoarg.pl): The inner quotes quote the space, making it one arg: echoarg foo\bar foo\bar = foobar = foobar The outer quotes have the same effect: echoarg foo\bar foo\bar = foobar = foobar Removing outer and inner produces a single arg: echoarg foo\bar foo\bar = foobar foobar No backslashes: echoarg foobar foobar = foobar foobar Effects of inner quotes w/ outer quotes w/o outer quotes = = echoarg foobar echoarg foobar = foobar = foobar echoarg foobar echoarg foobar = foobar= foobar echoarg foobar echoarg foobar = foobar= foobar echoarg foobarechoarg foobar = foobar= foobar echoarg foobar echoarg foobar = foobar = foobar echoarg foobar echoarg foobar = foobar = foobar Ick, Ick, Ick. There are also differences between cmd.exe and command.com, not to mention differences in releases and differences that depend on extensions being enabled. Ick. -- 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/where to install xyz.pm from CPAN (no perl Makefile.PL; make; make test; make install)??
On 10/11/2004 11:01 PM, Ken Wolcott wrote: Hi; I see several very interesting CPAN modules regarding Rational/IBM ClearCase. These are just *.pm files. How/where do I install these? I have root privs. I want the modules to be available in the standard place(s). I guess I should just look at the %INC hash and place it in a good location? A more general question along the lines of giving me a fishing pole instead of giving me a fish...I can go to (http://groups.google.com/groups?hl=enlr=ie=UTF-8group=perl.beginners) to search for archived postings, but what meaningful search string would I provide in order to obtain answers pertinent to my question above? I have the 3rd edition of the camel book and refer to it frequently. I have several other perl books (mostly O'Reilly) as well. I don't remember seeing this topic addressed. In general, you should never manually drop in modules. Is there no Makefile.PL or Build.PL file with the module? If not and it is on CPAN, the author should have his or her @$$ kicked. =) What module(s) are you looking at? Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Compiling and distributing Perl
On 10/7/2004 2:43 PM, Karl Kaufman wrote: Thanks for the reply, Jenda. (OS/arch is Solaris8/Sparc) The difficulty will be knowing exactly which files were added by a module install -- if I want to distribute per module. Otherwise, I guess I can just roll the updated site_perl directory structure. Yes? From: Karl Kaufman [EMAIL PROTECTED] Ok, I have a sane compiler toolset installed on my development server, but NOT on several servers on which I want Perl. (Where the development and production servers are the same architecture.) Can I build install Perl on my development server, and then just distribute it as a tarball to the production servers? I think that there are configure and MakeMaker options to explicitly support what you are trying to do. This is what the package maintainers like dep and rpm use. But I've never really looked into it myself and I'm on a Windows box right now, so I can't easily check. Have you looked at all the options? Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Upgrading from version 5.8.0 to 5.8.5 on Solaris
On 10/6/2004 6:21 PM, Eduardo Vázquez Rodríguez wrote: I have the following questions 1. Doing that, how do I use the new perl binary 5.8.5 instead of the old 5.8.0? I believe that /usr/local/bin/perl is pointing to the older version instead of the newer It's just a link to the versioned executable. Change the link to point to /usr/local/bin/perl5.8.5. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Regex for logwatch report
On 10/5/2004 10:25 PM, Kevin Old wrote: Hello everyone, I'm parsing a Logwatch report I get daily from my server and have hit a snag. I'd like to grab everything between the pam_unix Begin line and the pam_unix End line. - pam_unix Begin sshd: Invalid Users: Unknown Account: 17 Time(s) Authentication Failures: admin (ym74043.ym.edu.tw ): 4 Time(s) root (ym74043.ym.edu.tw ): 3 Time(s) unknown (ym74043.ym.edu.tw ): 17 Time(s) -- pam_unix End - The code I have is (assuming the entire report is in $body): $body =~ / \-+\spam_unix\sBegin\s\-+ \((.*)\s*\) #matchline \-+\spam_unix\sEnd\s\-+ /sx; This is where the .. range operator is useful: while (defined( my $line = INPUT )) { if ( /-+ pam_unix Begin -+/ .. /-+ pam_unix End -+/ ) { # between beginning and end } } See `perldoc perlop`, section Range Operators -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Regex for logwatch report
On 10/5/2004 10:36 PM, Randy W. Sims wrote: while (defined( my $line = INPUT )) { if ( /-+ pam_unix Begin -+/ .. /-+ pam_unix End -+/ ) { # between beginning and end } } err, that was obviously not tested. Should be: while (defined( my $line = DATA )) { if ( $line =~ /begin/ .. $line =~ /end/ ) { # between beginning and end } } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: First module
On 9/14/2004 8:22 PM, Johnstone, Colin wrote: Gidday all, I have written a module to be used with our CMS 'Teamsite' I wonder if any of you Perl gurus can see any holes in this. It has methods to return the following 1) branch path 2) branch name 3) workarea 4) local path any help appreciated thank you Colin given the following file path for example /.iwmnt/default/main/det/oli-intranet.admin.tafe/WORKAREA/work/templatedata/Navigation/PrimaryMenu/data/primarymenu #!/web/teamsite/iw-home/iw-perl/bin/iwperl package detir::SystemData; sub new { my ($proto, $dcrPath) = @_; my $class = ref($proto) || $proto; my $self = {}; ( $self-{BR_PATH}, $self-{BR_NAME}, $self-{WA_NAME}, $self-{L_PATH}) = $self-getParts($dcrPath); Does the above call actualy work? At this point $self is just a reference to a hash. You need to bless it before you can call methods on it. bless $self, $class; return $self; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Conceptual questions about 'pack'
Bee wrote: - besize template 'aAuU', anything else tempplate I can use to prepare fix length data ? - if yes, but how do I assuming the block size is? In case, if I write a binary file and I wanna use seek. You are going to have to explain that in more detail. In case, I am doing something like a log with User v TimesOfSignIn. So, user name will set as 30 char long, and the Signin times is about in scope of a normal integer. I wanna make this a simple DB for this but not a list of single files for each user. So I wanna make this doable for ramdom read write, so, that should be in a binary file. You want to have a look at DBM files. Read perldoc DB_File or perldoc SDBM_File Or you may try to install DBD::SQLite. That would give you the full power of SQL without having to install anything but the module. However, as the file is in a binary, I think there could be a size benfit for me to compress the data length. Premature optimization is the root of all evil. How many users are we talking about? Millions? I would not sweat over a few KB you might save. Yes, that's very right, I should have to do that with some db modules!!! I am sorry I missed something to declare here . I just do it as an experiment to know and learn how pack works in this ways. So, I still looking for a pack way to get this job done. Actaully, I am still quite confuse on what I can expect pack and unpack can giving help to me, in furture. I guess I would have some light to know what pack is while this get done. pack and unpack simply provide a way to translate the bits of a string in a specific way. eg. you can look at a string of bits as a series of 32-bit signed integers or you can look at the same string as a series of 8-bit characters. (It's sort of like a casting operator in C/C++.) It provides a way of looking at or storing data in a very specific way. It's primary use is looking at or creating binary data to be shared with other (C-like) applications. Randy. -- 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 routine syntax
Mike Blezien wrote: Hello All, We've been revamping alot of our older perl scripts and a question came up that I wasn't a 100% clear on. When calling sub routines, is there a significate difference in these formats: 1) some_subroutine(); 2) some_subroutine; This syntax has the special property that it passes the arguments of the current sub into the sub being called: #!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub a { print 'a: ' . Dumper([EMAIL PROTECTED]); b; } sub b { print 'b: ' . Dumper([EMAIL PROTECTED]); } a(1,2,3); __END__ 3) some_subroutine(); is one a more prefered or more effecient to use then the other(s)?? use (1) -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Elegant sequencing
On 8/29/2004 2:36 AM, Bryan Harris wrote: I don't claim to be a master, but you can do something along the lines of: $range = '4.3:8.3'; $range =~ /(\d+).(\d+).(\d+).\2/ and print map $_.$2 , $1 .. $3; Since it appears you require that the fractional part be the same for both ends of the range, I'm just capturing the integer parts and using Perl's range operator to build the list to feed to map() I do have a question, I notice you use and like an if..then. What if you wanted to do two things if that =~ held true? Is that possible? Yes. if ( $range =~ /(\d+).(\d+).(\d+).\2/ ) { print map $_.$2 , $1 .. $3; # do something else } I actually meant doing 2 things using the-- statement 1 and statement 2; -- syntax. I thought there was a way to use braces to enclose a set of statements as if it were one, but I could never get it to work in this type of statement... Of course. This is Perl: condition and do { statement1; statement2... } BUT, the way John suggested is The Right Way to do it. Complex statements are more difficult to interpret by humans, are more prone to be buggy, and are difficult to debug. Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: utility to install modules
On 8/26/2004 11:39 PM, Chris Devers wrote: On Thu, 26 Aug 2004, Joe Echavarria wrote: Trying with /usr/sfw/bin/ncftpget to get ftp://ftp.perl.org/pub/CPAN/MIRRORED.BY ftp.perl.org: unknown host. ncftpget: cannot open ftp.perl.org: unknown host. Can you ping this host? Can you FTP to it? It sounds like this machine is either unconnected from the Internet or maybe it doesn't have working DNS or something. In any case, it sounds like a general network failure that is happening deeper down in the system than Perl / CPAN.pm is working at. You need to figure out what is up with this machine's network connection, and make sure that you can interact with remote FTP servers, before you'll be able to get anywhere with the CPAN shell. Also, If your behind a firewall, read the special instructions in `perldoc CPAN.pm` in the section WORKING WITH CPAN.pm BEHIND FIREWALLS. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Sed-type-function
Dave Kettmann wrote: List, Does perl have any built-in sed-like function? I found ASED.pm, but would rather go with something built in. I looked around a bit, but didnt find anything. I guess I could go with using the Shell module but would rather using as few modules as possible. I'm not sure what you mean by sed-like function. Perl can do anything sed can do. There is also a script that converts sed to perl, see `perldoc s2p` -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Regex problems
me wrote: Hello all, I have been beating my head against the wall for a while trying to extract some data. Here is the following data: SNIP My goal is to put all data after each colon into a variable. I don't have any problem with Data 1 through Data 4. My problem is when I get to Data 5:, I can't figure out how to put the data into a variable. #!/usr/bin/perl use strict; use warnings; my %data; my $cache; while (defined( my $line = DATA )) { chomp( $line ); if ( $line =~ /\w+:/ || eof(DATA) ) { $cache .= $line if eof(DATA); my( $k, $v ) = split( /:/, $cache, 2 ); $data{$k} = $v; $cache = ''; } $cache .= $line; } use Data::Dumper; print Dumper( \%data ); __DATA__ Data 1: data1 Data 2: data2 Data 3: data3 Data 4: data4 Data 5: data5 data5 data5 data5 data5 data5 data5 data5 data5 data5 data5 data5 -- 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 installing Archive::Tar
Ronald Nutter wrote: I am trying to install this module for use with a spamassassin server. Using Perl 5.8.3 on Fedora Core 2. Getting the following error when I either try to install the module through CPAN or downloading the tar and doing it the old fashioned way. Would appreciate any suggestions for finding the problem. I am new to linux but am trying to learn. Two things. First, when the test suite fails, re-run it setting TEST_VERBOSE=1 to find out exactly where the error is occuring. Second, if there are problems related to I/O and you're running perl 5.8.x, you need to check your environment settings related to language, i.e. LANG the LC_* variables. Since not all modules are unicode ready, there /may/ be problems for anything other than LANG=C. Randy. -- 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
On 8/19/2004 7:40 PM, Subrata k Bose wrote: snip / It is extremely inapropriate to CC questions to so many people who are already members of the mailing list. If you have a question, simply post it to the list. Regards, Randy. -- 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 simple request need help
On 8/19/2004 12:06 AM, Bee wrote: Hi, I have a script that ables to download sort of web pages automatically by certain time. I use LWP::UserAgent to get almostly my job done, but this time, I have a problem that the page require to send back cookies and http_referer... It there anyway I can do this with LWP ? or should I back to HTTP::Request ? or what ? I am not familiar with Object playing, so if there is a short piece of code can demostrate, that would be very nice. Is this what you're looking for: http://tinyurl.com/4x7tg ? -- 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 write a script
Singh, Harjit wrote: The following code is what I used to check if item number could be detected for the file I sent in the earlier email. The code seems to have failed and need a advise on it.. A couple of suggestions/corrections: #!C:\perl\bin\perl5.6.1 use strict; use warnings; $file1 = ' C:\perl\bin\dummy.txt' ; open (INFO, $file1 ) or die Can't open $file: $1; while (INFO) This assigns each line in turn to the special variable $_ { if ($test = ~ /2\.2\./d+\./d+\./d+){ so, matching against $test, which is undefined, does nothing. Also, the regular expression should not be in quotes. What you want to do is match the regular expression againg $_ and capture the data you want using the regular expression capture operator (). Using your above expression that would be something like: if ( $_ =~ /2\.2\.(/d+)\.(/d+)\.(/d+)/ ){ or since the $_ variable is implied, it can be shortened to: if ( /2\.2\.(/d+)\.(/d+)\.(/d+)/ ){ print $test \n ; }} Using the above captures, your results will now be in the variables $1, $2, $3. close (INFO); -- 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 write a script
Singh, Harjit wrote: Randy, The code is still not working with the modifications that you listed earlier. The code does not have any compilation errors but does not show the results for the variables $1, $2 and $3. I was wandering if you could think of something else that is causing the problem. #!C:\perl\bin\perl5.6.1 You forgot: use strict; use warnings; $file1 = ' C:\perl\bin\dummy.txt' ; my $file1 = ' C:\perl\bin\dummy.txt' ; open (INFO, $file1 ) or die Can't open $file: $1; ^^ Your die message uses a different variable ($file vs $file1). And you probably meant $! vs $1 to display the error message. open (INFO, $file1 ) or die Can't open $file1: $!; while (INFO) { if (/2\.2\.(\d+)\.(\d+)\.(\d+)/) { print $1,$2, $3 ; }} close (INFO); Despite the problems mentioned above, I'm not sure why it didn't work for you. Your code works as is for me with a dummy.txt file of, eg. 2.2.100.200.300 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: iterate over the fields of a struct?
Christopher J. Bottaro wrote: is there a way to iterate over the fields of a Class::Struct (in the order they were declared)? No. You could store the data used to generate the struct, and then use it later. my @struct_data = [ key1 = 'type', key2 = 'type', ]; struct Name = [EMAIL PROTECTED]; then iterate of @struct_data... yeah i know its a long shot, but perl sometimes does things for me that i never would have believed...much less knew to expect...;) also, i know you can do this with hashes (although in random order, unless you sort the keys), but hashes are too error prone for my liking. i.e. $my_hash{TYPO} = $blah; does not result in an error...=( If you're using version 5.8 or later you can use restricted hashes. See `perldoc Hash::Util` Randy. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Sorting an array of hashes
On 8/5/2004 5:18 PM, Chris Mortimore wrote: I want to sort an AoH. Not each hash by its keys, but the array by the value of one of the keys in each hash. I know how to sort a simple array. I know how to sort a hash by the keys. Could someone kindly point me to the documentation on sorting arrays of hashes? `perldoc -q sort` Ex. my @AoH = ... my @sorted = sort { $a-{key} cmp $b-{key} } @AoH; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Testing for empty value
On 8/5/2004 6:23 PM, Jenda Krynicky wrote: From: mike [EMAIL PROTECTED] I have the following code print date times,@date,br; if ($ti1){ print time 1 is not empty; } else { print time 1 is empty; } If there is a value it works but not if there isn't ie: if there is a value it prints time 1 is not empty, but if there is not nothing comes out anyone any ideas? Sounds strange. Could you send us a small complete script that would display the problem? Something we could run and see that it doesn't print anything even though (you belive) it should. WAG, but maybe this: if ($ti1) { should more properly be written as: if ( defined($ti1) length($ti1) ) { -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Testing whether an array has any elements in it
On 8/5/2004 11:39 PM, Edward Wijaya wrote: Hi, Is there any efficient way to do that? scalar( @array ) Returns the number of elements in an array. It is a constant time operation; the number of elements is stored as part of the internal data structure, so it's just a lookup. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Number formatting
On 8/4/2004 10:02 PM, [EMAIL PROTECTED] wrote: Hi all, I am doing conversions from square metres to square feet for example. I have a regex that removes any commas or spaces in a number. I then do the conversion return an integer but then want to display the number with the commas or spaces put back in to make it easier to read. Number::Format -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: Module to merge arbitrary multi-level data structures?
Randy W. Sims wrote: Does anyone know of a module that can take a reference to two arbitrarily organized data structures, and return a merged structure? Scratch that. Hash::Merge seems to do what I want. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Module to merge arbitrary multi-level data structures?
Does anyone know of a module that can take a reference to two arbitrarily organized data structures, and return a merged structure? Thanks, Randy. -- 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 Core
On 7/31/2004 12:24 PM, James Edward Gray II wrote: Quick question: What's the best way to find out if a module is standard in the Perl Core and if it is, when it was added? Check out Module::CoreList http://search.cpan.org/dist/Module-CoreList/ -- 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 Core
On 7/31/2004 12:40 PM, James Edward Gray II wrote: On Jul 31, 2004, at 11:30 AM, Randy W. Sims wrote: On 7/31/2004 12:24 PM, James Edward Gray II wrote: Quick question: What's the best way to find out if a module is standard in the Perl Core and if it is, when it was added? Check out Module::CoreList http://search.cpan.org/dist/Module-CoreList/ perl -MModule::CoreList -e1 Can't locate Module/CoreList.pm in @INC (@INC contains: snip Guess that leads me to the question, when was Module::CoreList added? It's not in the core. The perldeltaxxx files have info on when modules are added or modified, but I don't recall a complete list being in the docs anywhere. If you don't want to or can't install Module::CoreList, you can pick out the info online from: http://search.cpan.org/src/RCLAMP/Module-CoreList-1.96/lib/Module/CoreList.pm -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: howto 'cat file|grep foo bar|wc -l' in perl
Maurice Lucas wrote: Hello, I just started using perl and want to rewrite a simple bash script i've been using in the past to perl. I want to cat file|grep foo bar|wc -l and tried it the following way which worked for foobar as one word and not as two words. --- #!/usr/bin/perl $logfile = /var/log/logfile; $grep_cmd = /bin/grep; $string = $ARGV[0]; $count = 0; open(LOG, cat $logfile|$grep_cmd $string|) || die Ooops; ^^^ When interpolated, $string can show up as multiple words. You need to quote it by surrounding it with single quotes, but... while($line = LOG) { $count++; } print $count\n; --- calling this program with ./count.pl foobar works and with ./count.pl foo bar doesn't works neither does ./count.pl foo bar works How do I write this the right way? You can easily do all this in perl. You're nearly there in your example above. Just open the file instead of the pipeline you have above. Then in your while loop, increment $count only if $line =~ /$string/. Randy. commandline alternative: perl -nle '$c++ if /foobar/;END{print $c}' /var/log/logfile -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response
Re: sort by extension
perl.org wrote: On Thu, 29 Jul 2004 12:08:20 -0400 (EDT), Jeff 'japhy' Pinyan wrote That's why he broke it down. Is the map() really the problem, or is it the regex, the ?: operator, and the two array references? All of the above ;), but now that I think about it the map looks easiest, then ?: (which I also prefer not to use, along with unless). At least map is a word instead of a (cryptic) token. map() is easier to understand if you rearange it a bit. Take the expression you've been discussing: map { m/\.([^.]+)$/ ? [$_, $1] : [$_, ''] } @input; Well, let's make it a complete expression my @results = map { m/\.([^.]+)$/ ? [$_, $1] : [$_, ''] } @input; Let's add a little formatting: my @results = map { m/\.([^.]+)$/ ? [$_, $1] : [$_, ''] } @input; Change the spelling of map and rearrange a bit: my @results; foreach (@input) { push( @results, m/\.([^.]+)$/ ? [$_, $1] : [$_, ''] ); } We can change the spelling of that ?: thingy too: my @results; foreach (@input) { if ( m/\.([^.]+)$/ ) { push( @results, [$_, $1]; } else { push( @results, [$_, '']; } } Let's be a little more specific about what we're working with: my @results; foreach my $file (@input) { if ( $file =~ m/\.([^.]+)$/ ) { push( @results, [$file, $1]; } else { push( @results, [$file, '']; } } That is easier to read. It's more obvious what is going on. I hardly ever write code like this. ;-) For better or worse, I've gotten use to the terseness that perl is capable of. The original map expression reads just like good prose to me. I guess a person can get used to about anything. Actually, there does seem to be an advantage to the terseness: it seems to help me comprehend larger chucks of code when reading unfamiliar code. The above is not the greatest example, but you can see that in the rearranged version you have to read about a half dozen lines to figure out what is going on whereas in the original, it's one line. I can't say which is better, terseness or verbosity. I can say that I had very similar opions to yours when I first encountered perl. I come from a C/C++ background, and I like minimalist languages. The fewer constructs in a language, the fewer the complexities, the fewer the problems. I remember reading the camel book and hating all the ways of saying if/else/unless, amoung other things. Too many ways to do it (TMWTDI). I would never use some of those extraneous constructs... Oh well, so much for first impressions. I'm now a sinner with the worst of them. There's not a construct I won't abuse. I glory in terseness. I spend untold amounts of time trying to sqeeze two expressions into one. I spend precious cycles pouring over sections of code not because it doesn't work, but because it doesn't look right... esthetically. I want to find ways to restructure my code... poetically. Confused? -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/ http://learn.perl.org/first-response