AW: Subroutine

2010-10-11 Thread Thomas Bätzler
Jyoti jcutiep...@gmail.com asked:
 Can anyone help me out to call all subroutines from different .pm files
 in a specific directory please?

Maybe if you were a bit more specific about what you're tyring to do.

Maybe you want to start out by looking at 
http://search.cpan.org/~adamk/Class-Inspector-1.24/lib/Class/Inspector.pm to 
figure out which methods are exported by a class.

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: testing tcp connection

2010-09-01 Thread Thomas Bätzler
Kammen van, Marco, Springer SBM NL marco.vankam...@springer.com asked:
 I have an issue when something goes wrong with the client that's trying
 to connect.
 
 9 out of 10 times this works fine, but there are odd situations where
 $clientip doesn't get filled in, which leaves me with a connection I
 can't do anything with...
 
 I tried to use close($client) to just terminate these odd connections
 when $clientip is empty but that doesn't work..

From my understanding of sockets (strictly limited ;-)) you'll need to call 
$client-shutdown( $how ):

From perlfunc:

  shutdown SOCKET,HOW
  
  Shuts down a socket connection in the manner indicated by HOW, which has the 
same interpretation as in the system call of the same name.

shutdown(SOCKET, 0);# I/we have stopped reading data
shutdown(SOCKET, 1);# I/we have stopped writing data
shutdown(SOCKET, 2);# I/we have stopped using this socket

  This is useful with sockets when you want to tell the other side you're done 
writing but not done reading, or vice versa.  It's also a more insistent form 
of close because it also disables the file descriptor in any forked copies in 
other processes.


HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Data migration

2010-07-27 Thread Thomas Bätzler
Shlomi Fish shlo...@iglu.org.il wrote:
 My suggestion is to simply copy the appropriate lines from the
 /etc/passwd to
 the new /etc/passwd.

... and of course not to forget about /etc/shadow because otherwise you won't 
be able to login.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: array to hash array

2010-07-26 Thread Thomas Bätzler
Sharan Basappa sharan.basa...@gmail.com asked:
 Can someone tell me how to convert an array to hash.
 
 Each array entry has a row of values
 e.g. a(0) = ab cd ef; a(1) = mn de fg
 
 The hash array needs to be constructed with one of the element in the
 array row as the key.
 e.g. hash{ab} = cd ef  - ab is a string in the array row
hash{mn} = de fg- mn is a string in the array row
 
 Can someone comment?

This works in the obvious way (pseudocode):

for each element in the source array:
compute the hash key from the element
compute the hash value that should be stored under that key
if the hash key doesn't exist yet
store the hash value 
otherwise
handle duplicate hash key

Which part is it that is giving you trouble?

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: hash arrays

2010-07-26 Thread Thomas Bätzler
Hi,

Sharan Basappa sharan.basa...@gmail.com asked:
 I am reusing a code for some enhancements. According to my
 understanding, it is a record with
 some unique string as key and then hash array as the value.
 
 I iterate through the array and print as follows:
 
 foreach my $key (keys %{$abc})
 {
   print $key ${$abc}{$key} \n;
 }
 
 I get values such like:
 val_0001 HASH(0x186c0060)
 val_0002 HASH(0x187ea490)
 val_0003 HASH(0x18655bc0)
 val_0004 HASH(0x1880fc60)
 
 Can someone tell me how to get the actual value instead of HASH* as
 above?

Assuming that $abc is a hash reference, it works like this:

#!/usr/bin/perl -w

use strict;

# $abc is a hash reference
my $abc = {
  'foo' = 1,
  'baz' = 2,
  'bar' = 3,
};


foreach my $key (keys %$abc)
{
  print $key $abc-{$key}\n;
}

__END__

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Compare file/dir size

2010-07-23 Thread Thomas Bätzler
HACKER Nora nora.hac...@stgkk.at wrote:
 Thanks for your input. Since both directories reside on different
 servers I would need a solution suitable for rexec. I have already
 thought about something like what you suggested, but then I discarded
 this idea because in my opinion a rexec for each file to get the stat
 would not be overly elegant!? I'll stand corrected...

You could run sha1sum (or md5sum or whatever you have) on the list of files you 
transferred, then comparte the output of both runs.

MfG,
Thomas Bätzler
-- 
BRINGE Informationstechnik GmbH
Zur Seeplatte 12
D-76228 Karlsruhe
Germany

Fon: +49 721 94246-0
Fon: +49 171 5438457
Fax: +49 721 94246-66
Web: http://www.bringe.de/

Geschäftsführer: Dipl.-Ing. (FH) Martin Bringe
Ust.Id: DE812936645, HRB 108943 Mannheim




AW: Query on Qunatifiers

2010-07-15 Thread Thomas Bätzler
Chandan Kumar chandan_28...@yahoo.com asked:
 I have query over quantifiers.
 
 Could you please explain the combination of operators Question mark
 (?),dot(.),star(*),plus(+).
 
 Say this is my string:
 
 $_ =  this is my first pattern ,quite confused with quantifiers
 
 ex: (thi.*?) or (thi.+?) etc
 
 I know what each operator does if used seperately,but combination of
 these operators are confusing.

You should really read the provided documentation - Uri posted about that to 
the list just a short while ago ;-)

Please note that . is not a quantifier. ?, + and * are.

In RE, a . by itself is the atom that matches any one character.

The quantifiers mean:

? 0 or 1 occurences of the previous expression.
+ 1 or more occurrences of the previous expression (greedy match).
* 0 or more occurrences of the previous expression (greedy match).
*? 0 or more occurrences of the previous expression (parsimonious match).
+? 1 or more occurrences of the previous expression (parsimonious match).

The difference between greedy and parsimonious matching is that in a greedy 
match, the longest possible match will be tried first whereas in a parsimonious 
match, the shortest match will be tried first.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: question abt array

2010-06-30 Thread Thomas Bätzler
Chaitanya Yanamadala dr.virus.in...@gmail.com asked:
  i am in a situation like i have a scalar $value = 5
 now i need to create an array with the number i mean $value
 how can i do it??

Don't even think about messing with the symbol table, use a hash variable 
instead:

my %hash;

  my @array = qw(foo baz bar);

my $value = 5;

# store reference to an array in the hash element $key
  $hash{ $value } = \...@array;

$hash{ 7 } = [ 'eni', 'miney', 'moo' ];

  # accessing data, e.g. 1st Element in array 5.
  print $hash{ 5 }-[0];

Using a hash makes sure there are no unwanted side effects like you 
accidentally overwriting some variable required elsewhere.

If you gave a better description of what you wanted to achieve - as opposed to 
what you think you need to do - I'm sure people here would be able to help you 
better.

HTH,
Thomas


AW: Multi page form - cgi

2010-06-28 Thread Thomas Bätzler
Herb patyoun...@hotmail.com asked:
 I've been working on putting together a multi-page form in a single
 perl script.  I have everything working as a single page form (writing
 to mysql database and emailing the output upon submit) but have not
 had any luck breaking the form into multiple pages.  As mentioned
 before, I'm not an everyday perl programmer so I may be going about
 this whole thing wrong.
 
 I'm trying to break 20 parameters into 4 pages as:
 
 if ($param1 eq ) {
 
 display page1
 
 } elsif ($param6 eq ) {

I'd suggest that you use one CGI parameter for page selection. My personal 
preference is to call it action and give it meaningful values, like:

use CGI;
use CGI::Carp qw/fatalsToBrowser/;

my $q = CGI-new();

[...]

my $action = $q-param('action') || '';

if( $action eq update ){
  # display update page
} elseif( $action eq insert ){
  # display insert data page
} else {
  # display start/login page
}

Using a single action parameter avoids ambiguities when deciding which page 
to display.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Multiple background processes

2010-06-24 Thread Thomas Bätzler
HACKER Nora nora.hac...@stgkk.at asked:
 I am currently having an issue with background processes. I already
 searched the web and found a way how to principally send a process into
 background, wait for the execution to finish and then go on with the
 main program:
 
 my $pid = fork;
 if ( $pid ) {
 wait;
 print done.\n;
 } else {
 print starting.\n;
 system compress *.dbf ;
 exit;
 }
 
 The done. is being issued at the correct point of time, namely when
 really all files have been compressed. Unfortunately, this only
 compresses one file after the other and therefore lacks performance. So
 I tried to send multiple processes into background and have them to be
 executed simultaneously. I tried the following:
 
 my $pid = fork;
 if ( $pid ) {
 wait;
 print done.\n;
 } else {
 print starting.\n;
 foreach ( glob *.dbf ) {
 system compress $_ ;
 exit;
 }

Have you had a look at the perlipc manpage yet? I'd say it's mandatory reading 
for what you're trying to achieve.

Apart from that, spawning multiple cruncher processes makes sense - up to a 
point. Obviously you don't want to spawn more processes than the number of CPU 
cores in your system because then they would be in contention for CPU.

Fortunately, there's already at least one module on CPAN that does most of the 
hard work for you: 
http://search.cpan.org/~dlux/Parallel-ForkManager-0.7.5/ForkManager.pm

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: A subroutine to find every occurrence of a substring in a string?

2010-06-10 Thread Thomas Bätzler
Peng Yu pengyu...@gmail.com asked:
 I can't find an existing perl subroutine (in the library) to find
 every occurrence of a substring in a string. The following webpage
 Example 3b. How to find every occurrence uses a loop to do so. But
 I'd prefer a subroutine. Could you let me know if such a subroutine is
 available in perl library?

If there isn't one, just roll your own:

#!/usr/bin/perl -w

use strict;

sub find_match {
  my( $text, $match, $offset ) = @_;

  $offset ||= 0;

  if( $[ - 1  ( $offset = index( $text, $match, $offset ) ) ){
return( $offset, find_match( $text, $match, $offset+1) );
  }
}

my $text = 'abaabaabaaababaaabaaabaababaabbbaabaabaaab';
my $match = 'aab';

print matches found at: , join(', ', find_match( $text, $match ) ), \n;

__END__

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Perl file with arguments

2010-06-09 Thread Thomas Bätzler
Gopal Karunakar gk.kalipuray...@gmail.com asked:
  How can i declare a simple perl script file which will take
 arguments from the user? an example will be take two numbers and
 give the sum as output.

Do you want to pass the arguments on the command line or prompt for them after 
starting your script?

In the first case use the @ARGV array. Its elements are the arguments your 
program was started with, e.g.

#!/usr/bin/perl -w

use strict;

if( 2 == @ARGV ){
  my $sum = $ARGV[0] + $ARGV[1];
  print The sum of $ARGV[0] and $ARGV[1] is $sum.\n;
} else {
  # wrong number of arguments
  print Usage: $0 number number\nprints the the sum of two numbers passed 
as arguments\n;
}
__END__

In the second case, use the STDIN filehandle, e.g.

#!/usr/bin/perl -w

use strict;

print Enter a number: ;
chomp( my $sum1 = STDIN );

print Enter a second number: ;
chomp( my $sum2 = STDIN );

my $sum = $sum1+$sum2;
print The sum of $sum1 and $sum2 is $sum.\n;

__END__

Input sanitation and validation in these examples is left as an exercise for 
the reader ;-)

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: an odd conditional statement

2010-06-09 Thread Thomas Bätzler
sillymonkeysoftw...@gmail.com sillymonkeysoftw...@gmail.com asked:


 I'm working with some customizable data from a config file, and can't
 for the life of me figure out how to test conditionals from an
 external source.
 Does anyone have an idea how to accomplish something like:
 
 my $statement = 1  10 and 2  10;  # obviously false
 my $result = ($statement) ? 1 : 0;# conditional test
 
 Now, $result will always be true(1), because the conditional is
 really, in effect, just validating that $statement is a defined
 scalar, not testing the statement.
 But, how can I perform an actual conditional statement on this?
 What I really want is:
 
 (1  10 and 2  10) ? 1 : 0;

You can do something like

my $cond = eval( $statement );

if( $@ ){
# an error occurred while evaluation $statement
# 
} else {
# $statement was o.k.; normal program flow
my $result = eval($statement) ? 1 : 0;
# rest of code
}

The two important things to keep in mind:

1) Make sure you sanitize $statement very carefully. Otherwise people can run 
arbitrary perl commands and you probably don't want that.

2) Check $@ after calling eval to see wether the code could be executed or 
wether it caused an error.

HTH,
Thomas



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Value betwwen quotes

2010-06-04 Thread Thomas Bätzler
Chaitanya Yanamadala dr.virus.in...@gmail.com asked:

 i have a string like this
 ComposedBlock ID=ZONE1-2 STYLEREFS=PAR1 HEIGHT=1062 WIDTH=1986
 HPOS=573 VPOS=3003
 
 i need to get the values between the   after the ID= . So how can i
 do it, Can any one help me??

Assuming the string is on a single line:

#!/usr/bin/perl -w

use strict;
use warnings;

my $line = 'ComposedBlock ID=ZONE1-2 STYLEREFS=PAR1 HEIGHT=1062 
WIDTH=1986 HPOS=573 VPOS=3003';

if( my( $id ) = ( $line =~ m/\s+ID=([^]*)/ ) ){
  print id value is '$id'\n;
} else {
  print no match found!\n;
}

__END__

Note that this method is fine for quickly grabbing a single value from a 
string, but highly unsuitable for parsing a complex xml document.

HTH,
Thomas


AW: Find duplicates in an array

2010-06-02 Thread Thomas Bätzler
Gopal Karunakar gk.kalipuray...@gmail.com asked:
 I needed to find all the duplicate values in an array and their count
 of occurences. Any help would be appreciated .

#!/usr/bin/perl -w

use strict;

my @array=qw(foo baz bar foo baz foo);

my %seen;

foreach my $item (@array){
  $seen{$item}++
}

foreach my $item (keys %seen){
  print item $item seen $seen{$item} times.\n
}

__END__

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Developer docs

2010-05-28 Thread Thomas Bätzler
Hi,

Steve Bertrand st...@ipv6canada.com asked:
 Is there a POD system that can be used exclusively for 'developer'
 documentation? Can I make devel docs 'hidden' from the rest of the POD?
 
 If not, can you recommend a decent practice that I can weave into my
 current documentation methodology so that people can still enjoy my
 user docs, while I can review my devel docs within a separate `perldoc'
 page?

Since you said weave... maybe you can use 
http://www.perl.com/pub/a/tchrist/litprog.html as a launch pad ;-)

Cheers,
Thomas



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Using Arrays and if loops together

2010-05-27 Thread Thomas Bätzler
Hello Niall,

niallheavey niallhea...@gmail.com wrote:
 I'm very new to perl but I will try to explain where I am at the
 moment.

Providing sample input and output is fine. However, if you need help with your 
code people here have to be able to look at it. Try and post a minimal example 
for the problem you're having - who knows, by trying to isolate the problem you 
might even find the solution yourself ;-)

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Good/best practice - pre-declare variables

2010-05-21 Thread Thomas Bätzler
HACKER Nora nora.hac...@stgkk.at wrote:
 Obviously, my point wasn't clear enough, I'm sorry for that. The
 variable in the code extract that I'm really bothering about is the
 $sdb: It is needed in the SWITCH of a sub-function, but this construct
 only works if I pre-declare the $sdb in the calling function backup(),
 even if it isn't needed for a $mode eq b but only for r.

Let's see if I understand this correctly:

You have a global variable $mode that's deciding the mode of operation in your 
sub dblog(), to quote:

 # DBLOG sub-function
 sub dblog {
my ( $backup, $dbvers, $sdb ) = @_;
SWITCH: {
( $mode eq b )  do {
print $fh_dblogsql insert into dbmovelog (DEBENAME, MOVE, 
 FELD1, FELD2, ERSTELL_TS) values ('.$db.', '.$mode.', '.$backup.', 
 '.$dbvers.', sysdate);;
last SWITCH;
};
( $mode eq t )  do {
print $fh_dblogsql insert into dbmovelog (DEBENAME, MOVE, 
 FELD1, FELD2, ERSTELL_TS) values ('.$db.', '.$mode.', '.$sdb.', 
 sysdate);;
last SWITCH;
};
}
}

Depending on the value of $mode, you run two slightly different SQL statements. 
The second of them with the wrong number of values ;-)

From the look of things, $backup and $sdb are really the same thing, namely 
input for the column FELD1. 

My gut feeling is that you should pass $mode as an argument to the function 
since it's never nice to have a subroutine that does two different things 
without an obvious reason.

I'd then coalesce $backup and $sdb into the variable $feld1 and suddenly you 
don't need your switch anymore.

Apart from that, there's really no need to call a three argument function with 
three arguments when you know you don't need the third argument.

Just call it with two arguments in that case, and the troublesome variable will 
be set to undef.

HTH,
Thomas




--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: print sub code

2010-05-21 Thread Thomas Bätzler
Tech list tech_l...@womenshealth.com asked:
 Let's say I have a module XYZ with a sub in it call ABC.  I'd like to
 print the source code of XYZ::ABC.
 
 My reason for this is I accidentally overwrote a module with an older
 version, but I still have httpd running which has it loaded in memory.

You can't print the source code since it's gone at that point. All that 
remains is the bytecode representation of that module. You can poke around in 
that using the B:: group of modules, like 
http://search.cpan.org/~jesse/perl-5.12.1/ext/B/B.pm. Beware, this is not for 
the faint of heart.

HTH,
Thomas

PS: Rule #1 of system administration and programming: _always_ make a backup.


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: data dumper

2010-05-17 Thread Thomas Bätzler
Bob McConnell r...@cbord.com asked:
 mBy saving the output of Data::Dumper to a *.pm file, it can be
 reloaded mvia use.
 
 What is the difference between this and exporting a YAML file? Where
 would either be preferred over the other?

You don't need a YAML parser to read in a Perl source file.

OTOH, it's easier to shoot yourself in the foot that way.


MfG,
Thomas Bätzler
-- 
BRINGE Informationstechnik GmbH
Zur Seeplatte 12
D-76228 Karlsruhe
Germany

Fon: +49 721 94246-0
Fon: +49 171 5438457
Fax: +49 721 94246-66
Web: http://www.bringe.de/

Geschäftsführer: Dipl.-Ing. (FH) Martin Bringe
Ust.Id: DE812936645, HRB 108943 Mannheim




--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Hash with variable name

2010-05-12 Thread Thomas Bätzler
HACKER Nora nora.hac...@stgkk.at wrote:
 The script is being started with a parameter $stp (among others) that
 can be one of mvb/pkv/av/be/vvw. This parameter is used as a key for a
 master hash the values of which are names of other hashes themselves.

 # Master-Hash
 my %stp_dirs = ( mvb = mvb_dirs,
   pkv = pkv_dirs,
   av = av_dirs,
   be = be_dirs,
   vvw = vvw_dirs );
 
 # AV
 my %av_dirs=( dir11 = dir12
   dir13 = dir14 );
 
 # BE
 my %be_dirs=( dir21 = dir22
   dir23 = dir24 );
 
 # MVB
 my %mvb_dirs= (dir31 = dir32
   dir33 = dir34 );
 
 # PKV
 my %pkv_dirs=( dir41 = dir42
   dir43 = dir44 );
 
 # VVW
 my %vvw_dirs=( dir51 = dir52
   dir53 = dir54 );

Try:

#!/usr/bin/perl -w

use strict;

# AV
my %av_dirs=(   'dir11' = 'dir12',
'dir13' = 'dir14' );

# BE
my %be_dirs=(   'dir21' = 'dir22',
'dir23' = 'dir24' );

# MVB
my %mvb_dirs= ('dir31' = 'dir32',
'dir33' = 'dir34' );

# PKV
my %pkv_dirs=( 'dir41' = 'dir42',
'dir43' = 'dir44' );

# VVW
my %vvw_dirs=( 'dir51' = 'dir52',
'dir53' = 'dir54' );

my %stp_dirs = ('mvb' = \%mvb_dirs,
'pkv' = \%pkv_dirs,
'av' = \%av_dirs,
'be' = \%be_dirs,
'vvw' = \%vvw_dirs );

while ( my($sdir,$tdir) = each %{$stp_dirs{'mvb'}}) {
print(SourceDir: $sdir\t\tTargetDir: $tdir\n);
}

__END__

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Hash with variable name

2010-05-12 Thread Thomas Bätzler
HACKER Nora nora.hac...@stgkk.at asked:
  Try:
 
  my %stp_dirs = ('mvb' = \%mvb_dirs,
  'pkv' = \%pkv_dirs,
  'av' = \%av_dirs,
  'be' = \%be_dirs,
  'vvw' = \%vvw_dirs );
 
  while ( my($sdir,$tdir) = each %{$stp_dirs{'mvb'}}) {
  print(SourceDir: $sdir\t\tTargetDir: $tdir\n);
  }
 
 Is that 'mvb' intentional? Also, I don't understand why to put '\%' in
 front of the values from the master hash. Nevertheless, I tried the
 alterations as suggested but the error remains:
 
 Can't use string (%mvb_dirs) as a HASH ref while strict refs in use
 at /opt/data/magna/wartung/tools/get_lieferung.pl line 145.

If you use strict; you may not use symbolic references, i.e. (mis)use a 
variable's name to create a reference to it. That's why I fixed your code 
by replacing the variable names with references to the variable I assumed you'd 
wish to address.

Maybe you should take a look at the perlref manpage (e.g. 
http://perldoc.perl.org/perlref.html) for a better explanation.

As for putting in a literal 'mvb' that was just to demonstrate the usage. Of 
course you can replace that with any expression evaluating to any key of 
%stp_dirs or whatever.

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Hash with variable name

2010-05-12 Thread Thomas Bätzler
HACKER Nora nora.hac...@stgkk.at asked:
 Thanks for your explanation and the reference to perldoc, I understand
 now. But it doesn't work yet, I still get the same error. I have
 altered my source now as follows:
 
 my %stp_dirs = ( mvb = \%mvb_dirs,
   pkv = \%pkv_dirs,
   av = \%av_dirs,
   be = \%be_dirs,
   vvw = \%vvw_dirs );
 [...]
 my ($sdir, $tdir);
 while (($sdir,$tdir) = each %{$stp_dirs{$stp}}) {
   DEBUG(SourceDir: $sdir\t\tTargetDir: $tdir\n);
 }
 
 Did I misunderstand anything?

Yes, you're using double quotes around the hash references.

Note how I wrote it:

my %stp_dirs = ('mvb' = \%mvb_dirs,
'pkv' = \%pkv_dirs,
'av' = \%av_dirs,
'be' = \%be_dirs,
'vvw' = \%vvw_dirs );

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: fork, read from child process and timeout

2010-05-11 Thread Thomas Bätzler
Weizhong Dai weizhong@gmail.com asked:
 -
 $pid = open(README, program arguments |)  or die Couldn't fork:
 $!\n;
 while (README) {
 # ...
 }
 close(README)
 --
 
 my problem is: I read from README, but if  waiting for next input is
 timeout, end reading. Is there any timer or method I could use for
 this purpose?

This code is probably better written as

my $program = ...;
my @arguments = ...;

my $pid = open( my $readme, '-|', $program, @arguments) or die Can't fork 
'$program': $!;

while( $readme ){
  ...
}

close( $readme );

(code OTTOH, please excuse any typos)

i.e. 
- use lexical variables 
- don't use a typeglob for your filehandle, use a lexical variable instead
- use three-argument open for increased safety

As for the timeout question, I assume what you want to do is this:
- read input from $program
- if there's no input, then stop reading after suitable timeout period

Something like that is usually done using select() as shown in the second usage 
example in http://perldoc.perl.org/functions/select.html

HTH,
Thomas



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: sort hash with an array as the value

2010-05-11 Thread Thomas Bätzler
Owen rc...@pcug.org.au asked:
 I have this statement;
 
 foreach my $key ( keys %filehash ) {
 print $key $filehash{$key}-[0]\t\t\t$filehash{$key}-[3]\t
 $filehash{$key}-[2]\t $filehash{$key}-[1]\n;
 }
 
 but wish to sort the output by $filehash{$key}-[0]. Is it possible?
 How do I do this?

foreach my $key ( sort { $filehash{$a}-[0] cmp $filehash{$b}-[0] } keys 
%filehash ){ ... }

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: IMAP email client: style security

2010-05-10 Thread Thomas Bätzler
Eitan Adler li...@eitanadler.com wrote:
 I wrote a program to fetch email from a IMAP account, look to see if I
 sent it, if yes execute any commands in the email and email the results
 back to via a SMTP server.
[...]
 2) Secondly since this program executes commands from a potentially
 insecure source I'd like to know if you find any security issues with
 my code. I used Mail::IMAPClient::get_header($_,From) to verify
 that I'm sending myself commands-- is this safe?
[...]

No. Mail headers are easily forged. You should probably be using PGP or S/MIME 
to authenticate your request. The request body should also include a request 
seqeuence number that you could use to guard against a replay-attack where an 
attacker would resend an old valid mail.

Cheers,
Thomas


AW: Remove and substitute character in a string with a regex

2010-05-10 Thread Thomas Bätzler
Finalfire blog.h...@gmail.com asked:
 Hello guys! I'm skilling regex using Perl and i've some trouble about
 a simple try:
 i've a string like:
 
 $string = HELLAAABB;
 
 and i want to manipulate in that way: HELL4O3ABB4C;You can simply
 notice that when i have 3 or more occurrences of a character, i want
 to substitute all the occurrences and write nC where n is how times
 the character C is found on a string.
 
 So, in regex (i think there are so many way to do it but i wish to do
 with regex, just skilling...) i write:
 
 $string =~ s/(.)\1\1+/$1/;
 
 but how can i get the number of the occurrences in the string of that
 pattern?

#!/usr/bin/perl -w

use strict;

my $string = HELLAAABB;

print $string\n;

$string =~ s/(.)\1{2,}/length($).$1/eg;

print $string\n;

__END__

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: AW: Remove and substitute character in a string with a regex

2010-05-10 Thread Thomas Bätzler
Hi Shlomi,

 use warnings is preferable to the -w flag.

Not in my book. The command line switch turns on warnings globally, whereas the 
use warnings; pragma only enables them in the current lexical scope. So by 
using the command line switch, I get warnings about crappy third-party code, 
too.

The only case where use warnings; might be better is if you're using a 
braindead shell/OS that doesn't look at the shebang line.

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: about dispatch tables

2010-05-06 Thread Thomas Bätzler
Harry Putnam rea...@newsguy.com asked:
 But even though I can work with that... I'm still not seeing why the
 values in @_ are not available at the call to N() inside like this:
 (incomplete code)
 
 func($val1,$val2);
 
 sub func { %h = ( N = sub { print N(@_) . \n; } ); }

If you call the sub like this, it'll create the hash %h containing the key N 
associated with a code reference to an anonymous subroutine. When that 
subroutine is called it will pass its _current_ argument list to function N, 
then print the returned values from that function and a line feed.

If you wanted that code reference to be called with the values of @_ at the 
time of its creation, you'd have to use a closure and keep a copy of the values 
in a lexical variable, probably a bit like this:

#!/usr/bin/perl -w

use strict;

sub label_closure {
  my $label = shift;
  return sub {
my $name = shift;

print $name, you're a $label!\n;
  }
}

my $laud = label_closure(genius);

$laud-('MJD');

__END__

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Directory sizes

2010-05-05 Thread Thomas Bätzler
HACKER Nora nora.hac...@stgkk.at asked:
 Unfortunately, this does not explain the difference between the local
 du and the one via rexec on a remote machine. Any help appreciated.

When you're getting different results then you're doing something differently 
;-)

For one thing, you're using just du to call the binary, so we can't be sure 
you're calling the same du in each case. So, when logged in on the remote 
machine, do which du and use the resulting fully qualified path in your rexec 
call.

Also, look at your environment (set and alias) on the remote machine to see 
wether you're getting additional options that way.

MfG,
Thomas Bätzler
-- 
BRINGE Informationstechnik GmbH
Zur Seeplatte 12
D-76228 Karlsruhe
Germany

Fon: +49 721 94246-0
Fon: +49 171 5438457
Fax: +49 721 94246-66
Web: http://www.bringe.de/

Geschäftsführer: Dipl.-Ing. (FH) Martin Bringe
Ust.Id: DE812936645, HRB 108943 Mannheim







--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: How to Decode UDP packets got from libpcap using Net::Pcap

2010-05-05 Thread Thomas Bätzler
perl perlatw...@gmail.com asked:
  I have used libpcap to capture data using Net::Pcap module
[...]
 This is an UDP DNS Query  How can i Decode them ... Any one Please
 help me

http://www.net-dns.org/docs/Net/DNS/Packet.html

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Array, foreach problem

2010-05-05 Thread Thomas Bätzler
Brian fulls...@me.com asked:


  foreach $line (LOGFILE) {
 
  while (my $line = $logfile) would be a better idea than
  foreach $line.
 
 Just curious for an explanation to this. I tend to use foreach too.
 Don't they both accomplish the same thing? :)

foreach (LOGFILE) means that the whole file will be read into memory and 
split into lines before the loop commences.

The second construct will just read in a line at a time, thus trading off speed 
for memory usage.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: about dispatch tables

2010-05-05 Thread Thomas Bätzler
Harry Putnam rea...@newsguy.com asked:
[...] 
 which is also inside sub dispt {the sub function}.  Where does global
 come in?

Hint: $code-(@_);

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: sendmail arguments

2010-04-29 Thread Thomas Bätzler
John Bruin john.br...@nec.co.nz asked:
 I have inherited a Perl script which sends and parses email. I
 am having trouble trying to figure out what the -oi and
 -oem arguments do in the sub below. Can anyone help?

-oemode sets the ErrorMode.

From http://www.sendmail.org/~ca/email/man/sendmail.html:

  ErrorMode=x
 
  Set error processing to mode x. Valid modes are `m' to mail
  back the error message, `w' to ``write'' back the error mes-
  sage (or mail it back if the sender is not logged in), `p' to
  print the errors on the terminal (default), `q' to throw away
  error messages (only exit status is returned), and `e' to do
  special processing for the BerkNet.  If the text of the mes-
  sage is not mailed back by modes `m' or `w' and if the sender
  is local to this machine, a copy of the message is appended
   to the file dead.letter in the sender's home directory.

And of course that's not a Perl question. The Perl question probably should be 
about how you can make your inherited code better.

While TIMTOWTDI, I would like to suggest using MIME::Lite for building and 
sending mails - see 
http://search.cpan.org/~yves/MIME-Lite-3.01/lib/MIME/Lite.pm#Sending

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Interactive shell in Perl

2010-04-28 Thread Thomas Bätzler
Parag Kalra paragka...@gmail.com asked:
 Wanted to know if Perl has any interactive shell (just like Python,
 Bash, Ruby etc have) by any chance. And if yes how do we invoke
 that.

Since you mentioned bash, the zoidberg shell might be an option:
http://search.cpan.org/~pardus/Zoidberg-0.96/man1/zoid.pod

HTH,
Thomas


AW: get path to linked directory

2010-04-27 Thread Thomas Bätzler
Andreas Moroder andreas.moro...@sb-brixen.it asked:
 I have a entry in my directory that is a soft-link to another
 directory.
 Is there a way in perl to get, starting from the link, the path of the
 real directory ?

http://perldoc.perl.org/Cwd.html#abs_path-and-friends

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Perl rounding errors?

2010-04-26 Thread Thomas Bätzler
Rob Coops rco...@gmail.com asked:
 I am just wondering if I sumbled upon an error in perl an error in my
 logic or somehtign else see the below perl one liners
 
 $ perl -e '$n = 0.945; $r = sprintf(%.2f, $n); print $r\n;'
 0.94

Short answer: You shouldn't use floating point numbers for financial 
calculations. Instead, calculate in cent-based integer values.

Long answer: perldoc -q round, perldoc perlnumber.

HTH,
Thomas





AW: why does this code fail with stat?

2010-04-22 Thread Thomas Bätzler
Harry Putnam rea...@newsguy.com wrote:
 I'm not finding a reference in perldoc File::Find showing how to set
 that flag when using the popular notation like the script involved
 here.

Probably a case of not seeing the woods because of the trees ;-)

To quote:

NAME
   File::Find - Traverse a directory tree.

SYNOPSIS
   use File::Find;
   find(\wanted, @directories_to_search);
   sub wanted { ... }

   use File::Find;
   finddepth(\wanted, @directories_to_search);
   sub wanted { ... }

   use File::Find;
   find({ wanted = \process, follow = 1 }, '.');
[...]

i.e.

find( { 
  wanted = sub {
  print $_\n;
  print $File::Find::name\n;
  if ($lastfld eq $_) {
print $lastfld matches $_; Lets check the size:\n;
my $size = (stat($File::Find::name))[7];
print $File::Find::name size: $size\n;
  }
}, 
no_chdir = 1,
  },
  $dir2
);

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Newbie stuck at the first hurdle

2010-04-22 Thread Thomas Bätzler
Kryten kryte...@googlemail.com asked:
 This is embarrassing.
 
 All I want to do is read the content of a simple 10 line .txt file
 into an array
 and print out the lines, and I just can't seem to get it to work!
 /*
 $target = D:\testfile.txt;
 open NEWBIE, $target;
 @arr = WAWA;
 foreach $line (@arr) {
 print $line\n;
 }
 close(NEWBIE)
 */

#!/usr/bin/perl

# always turn on warnings and enforce strict 
use strict;
use warnings;

# use lexical variables.
# modern Win32 knows about normal path separators, i.e. / instead of \
# use single quotes unless you want to interpolate the string i.e.
# include variables or escape sequences.
my $target = 'd:/testfile.txt';

# use a three argument open, use a lexical variable as a filehandle,
# check for result and die() giving an error on failure.
open( my $fh, '', $target ) or die Can't open '$target': $!;

# read the array from the filehandle you opened before
my @array = $fh;

# closing files is optional, but we're not messy programmers...
close( $fh );

foreach my $line (@array){
  # $line already has cr/lf; no need to add one more
  print $line;
}

__END__

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Meta: Nice Perl?

2010-04-22 Thread Thomas Bätzler
HACKER Nora nora.hac...@stgkk.at asked:
 I wonder if some of you are in the same situation like me: I am the
 only Perl programmer in the company, at least trying hard to get
 along :-), but I have nobody to ask for help. So I spend hours and
 hours with my book and the internet when I'm stuck. Luckily, so far
 I almost always accomplished what I wanted to do, but I don't know
 whether it is good programming - the scripts work, but if I compare
 them to some code that comes from the experienced guys here on the
 list they just look ... uhm, different ... How do you improve your
 scripts and in general your coding style without having someone to
 alert/advise you what could be improved?

- Many guidelines for good programming style apply to all programming languages 
in general - with the corollary being that the determined Real Programmer can 
write Fortran programs in any language[1]. Asking an experienced colleague 
about the subject might get you helpful pointers.

- Learn from other people's code. Try and figure out why they do certain things 
in certain ways. Code posted to this list by major contributors usually comes 
with an explanation why things were done in a certain way.

- Learn from your own mistakes, and find strategies to avoid or detect them. 
For example, back when I started learning C, I used to mix up = and == in 
comparisons. This led to many frustrating bug-hunts until I finally figured out 
that it's helpful to place constants on the left side in a comparison, so that 
I'd get a compiler error when I mistyped a comparison.

- Get in touch with other Perl programmers. I don't know where you're located 
in Austria but at least in Innsbruck and Vienna, there are Perlmonger groups. 
Attend a Perl conference like the annual German Perl Workshop[2] or 
YAPC::Europe[3] - they're very reasonably priced, so that you might even be 
able to convince your boss to pay for the trip as a training session. 

HTH,
Thomas

1) http://www.pbm.com/~lindahl/real.programmers.html
2) http://conferences.yapceurope.org/gpw2010/
3) http://conferences.yapceurope.org/ye2010/

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: AW: why does this code fail with stat?

2010-04-22 Thread Thomas Bätzler
Harry Putnam rea...@newsguy.com asked:
 I pointed to that exact piece of code then asked how to make that
 kind of options setting when using this format of find()
 
 find(
sub {
  if(bla){
blabla
  }
},
 @dir
 );

That's not possible, since there is neither an option parameter nor class 
variable by which you could change the behavior globally.
 
 Your proposed code
 
  find( {
wanted = sub {
print $_\n;
print $File::Find::name\n;
if ($lastfld eq $_) {
  print $lastfld matches $_; Lets check the size:\n;
  my $size = (stat($File::Find::name))[7];
  print $File::Find::name size: $size\n;
}
  },
  no_chdir = 1,
},
$dir2
  );
 
 doesn't do that.

It does however work as intended ;-)

HTH,
Thomas


AW: How to manage large Conditional Statement

2010-04-21 Thread Thomas Bätzler
Mimi Cafe mimic...@googlemail.com asked:
 I need to evaluate a statement in an if, elsif, else block, and the
 statement to evaluate in the elsif is too large as I need to run a SQL
 query and act on the return value.
 What would be a better way to achieve this? Putting the SQL statement
 elsewhere outside the block cannot be right, so I am wondering what to
 do here.

I'm talking for myself here, but the way I usually do this is that I wrap up 
each SQL query or set of related SQL queries in a subroutine.

If the sub's going to be used as a predicate I make sure it returns true/false 
and pass all of the relevant data as arguments. By giving it a suitable name, I 
end up with nicely readable code like

[...]
if( isSomeCondition( $foo, $baz, $bar ) ){
[...]

More or less straight out of Perl Best Practices, Chapter 3.

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Is there any method to tell different between warning and errors?

2010-04-20 Thread Thomas Bätzler
Jeff Pang armyw...@gmail.com wrote:

 On Tue, Apr 20, 2010 at 1:28 PM, Weizhong Dai weizhong@gmail.com
 wrote:
  Hi all,
  In my script, I have a system call, and redirect the stderr to a
 file.
         #
         # open STDERR, $workpath\\error_log.txt;
         # system ...;
         #
  but I only want the ERROR messages to be logged in the file. Is there
 
 try this:
 
 system command arguments 2error.txt;

That's exactly the same as re-opening STDERR, so it's not gonna help the OP.

So how to differentiate between warning and error message?

It all depends on the program's output. If the error messages are clearly 
tagged as such, one might try to filter STDERR by using IPC::Open3 to run the 
system command. That'll give the OP a distinct STDERR filehandle which he can 
read and parse, writing the interesting stuff to a logfile.

HTH,
Thomas


AW: Problems with show tech using the Net::Telnet Module

2010-04-20 Thread Thomas Bätzler
Asterix lange.gerh...@gmail.com asked:
 I've made a little script to capture the output of networking
 devices.
 Everything works fine, until I use the show tech command in an Cisco
 device.

Have you considered using the cmd() method of Net::Telnet? It has the option to 
individually set a reply timeout for each command:

#!/usr/bin/perl -w

use strict;
use Net::Telnet;

my $host = '42.42.42.42';
my $sysname = 'cisco';
my $login_pw = 'letmein';
my $enable_pw = 'secret';

my $tn = Net::Telnet-new( Host = $host ) ){
$tn-waitfor( '/word: $/' );
$tn-cmd( String = $login_pw, Prompt = /$sysname\$/ );
$tn-cmd( String = 'enable', Prompt = '/word: $/' );
$tn-prompt( /$sysname#\$/ );
$tn-cmd( String = $enable_pw );
$tn-cmd( String = 'terminal length 0' );
my @data = $tn-cmd( String = 'show tech', Timeout = 60 );
print @data;

__END__

Works fine for me on a 7206. YMMV.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Can't locate object method TIEHASH via package Apache::Session::MySQL

2010-04-19 Thread Thomas Bätzler
Owen rc...@pcug.org.au wrote:


 On Mon, 19 Apr 2010 00:14:44 +0100
 Mimi Cafe mimic...@googlemail.com wrote:
 
  I get following error when trying to open a session using
  Apache::Session::MySQL.
 
 
 
  Here is what I have
 
 
 
38   tie %session,  Apache::Session::MySQL, undef,{

There is leading whitespace in the class name  Apache::Session::MySQL.

 I really don't know, but the documentation shows;
 
 tie %hash, 'Apache::Session::MySQL', $id, {
 Handle = $dbh,
 LockHandle = $dbh
  };
 
 So did you try just the single quotes?

@Owen: If you really don't know then your suggestions are cargo cult 
programming. Please don't do that.

As a rule of thumb, use single quotes if you're dealing with a literal string 
than you don't want/need to interpolate (substitute variables, escaped 
characters, etc.) and use double quotes otherwise.


MfG,
Thomas Bätzler
-- 
BRINGE Informationstechnik GmbH
Zur Seeplatte 12
D-76228 Karlsruhe
Germany

Fon: +49 721 94246-0
Fon: +49 171 5438457
Fax: +49 721 94246-66
Web: http://www.bringe.de/

Geschäftsführer: Dipl.-Ing. (FH) Martin Bringe
Ust.Id: DE812936645, HRB 108943 Mannheim




--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Writing Perl scripts to run on any OS'es

2010-04-19 Thread Thomas Bätzler
newbie01 perl newbie01.p...@gmail.com asked:
 Am wanting to change my Perl scripts to get it to run on several UNIX
 flavours and Windows. At the moment, the only way I can think of how to
 accomplish that is always having the following checks on each and every
 sub that I have.
 
 Can anyone please suggest if there is a better way of doing this
 besides what am doing now? Am not sure whether creating a module
 for each OS to use is the solution although I don't know how to create
 a module anyway. I found one tutorial and get lost somewhere along the
 way on how to create a module ... :-)
 
 
 if ($^O eq 'MSWin32') {
 system dir $ARGV[0];
 }

Either this is a bad example or you're doing something wrong - listing a 
directory works well using the opendir()/readdir() commands in conjunction with 
the File::Spec::* family of modules for parsing and constructing path names. 
It's probably much less of a PITA to work with, too, since you don't have to 
parse 17 different output formats.

For other stuff, you should leverage the power of CPAN - search.cpan.org is 
your friend. For disk space usage for example, you might be able to use 
http://search.cpan.org/~iguthrie/Filesys-DfPortable-0.85/DfPortable.pm

As for creating your own modules, have you tried perldoc perlboot?

The absolute minimum to make and use your own modules goes something like this:

Decide where you want to keep your modules. For small projects I prefer to keep 
them in a directory called lib in the same directory as my Perl scripts. Perl 
needs to be told about that path, so I use the following code snippet in the 
header of my scripts:

use File::Spec::Functions qw( catpath splitpath rel2abs );
use lib catpath( ( splitpath( rel2abs $0 ) )[ 0, 1 ], 'lib' );

This tells perl to look first in my local lib directory that's in the same 
directory as the script (wherever that is).

Decide on your module namespace and the module name. Of course you're free to 
name your modules whatever you like, but the smart way is to create a hierarchy 
of names that identifies the module and its purpose, and add your company name 
or another unique identifier at the top level. So if you work for Quux, Inc. 
and you're writing a module that implements the Froob network protocol, you 
might want to name the module Quux::Net::Froob.

Note that the module name that you're going to use; must be reflected in the 
file's path name. So if you decide to keep your Quux::Net::Froob module in the 
subdirectory lib, it's relative path name would be lib/Quux/Net/Froob.pm. 
Please note that casing and spelling must be identical between module name and 
file path.

As to the contents of the module, a good starting point might be:

package Quux::Net::Froob;

use strict;
use warnings;

sub new {
my $class = shift;# 1st argument is class name
my $self = { };   # use empty anon hash to store instance 
variables
bless($self, $class); # bless the hash ref into an object
return $self;
}

sub set {
my($self, $data) = @_;
$self-{'data'} = $data;
}

sub get {
my($self) = shift;
return $self-{'data'};
}

1;
__END__

The 1; at the end of the module code is recommended since the module won't 
load if it's code doesn't evaluate to a true value during import.

To test your own module, try

#!/usr/bin/perl -wl

use strict;
use File::Spec::Functions qw( catpath splitpath rel2abs );
use lib catpath( ( splitpath( rel2abs $0 ) )[ 0, 1 ], 'lib' );
use Quux::Net::Froob;

my $foo = new Quux::Net::Froob;

$foo-set('blarg.');

print $foo-get();

__END__

If you're looking for a good book on Perl OO programming, I can personally 
recommend Object oriented Perl by Damian Conway 
(http://books.perl.org/book/171).
 
Hope this helps to get you started,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Problem in installing ActivePerl 5.10 on Windows 7 with x64 chipset

2010-04-15 Thread Thomas Bätzler
Hi,

Rene Schickbauer rene.schickba...@gmail.com wrote:
 For me, the msi packages worked quite well for the last few years.
 Altough i'm currently using the x86 versions due to some trouble with a
 few packages - mostly the ones that link to an external closed-source
 library, but i also had troubles with DBD::Pg.

As far as I can tell, the x64 version also ships without PerlScript support 
(perlse.dll).

Has anybody here successfully used the PerlScript engine of the x86 version on 
a x64 Windows system? If yes, pointers are appreciated ;-)

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Copy file from one server to another

2010-04-14 Thread Thomas Bätzler
Chris Coggins cacogg...@cox.net asked:
 I need to copy a small config file from one server to another. I'm
 generating the file on one server with a pretty complex script. I need
 to put that file on another server for immediate user access via html.
 I've tried just writing the file straight to the new server over the
 network using absolute paths but it doesn't work. I'm thinking that I
 can accomplish this instead through a perl-generated html page, to have
 the script copy the file from its source server and put it locally for
 use within the web page.
 
 What would the code look like to do this?

Let's see if I got this right: You have one server where some file is 
generated, and another one where said file is to be downloaded from.

Is this file personalized for each user, i.e. must arguments be passed from 
front- to backend?

If it's not personalized, can or should the file be cached on the frontend for 
period of time?

If the generation of the file is complex, can it be produced on demand or do 
we have to implement some kind of waiting mechanism that keeps the user's 
browser connected to the frontend while the file is generated?

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Perl get host's IP

2010-04-14 Thread Thomas Bätzler
pen...@nsbeta.info asked:

 Is there a general way to get linux OS's bound ip addresses? for
 example, the IP on eth0, eth1 etc. Thanks.

http://search.cpan.org/~lds/IO-Interface-1.05/Interface.pm could be a good 
enough solution for you.

I say good enough since it gives you all of the info that you'll get from 
ifconfig, which means that it's unaware of secondary ip addresses bound 
directly to the interface without using an interface alias like ethx:y. For 
that, you'll still need to parse the output from ip addr show (The command 
ip is part of the iproute2 suite, see 
http://www.linuxfoundation.org/collaborate/workgroups/networking/iproute2).

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: html print

2010-04-12 Thread Thomas Bätzler
Chris Coggins cacogg...@cox.net asked:
 I'm having trouble getting a piece of data from a form input to print
 in html. Here's the relevant portion of my code
 
 sub subroutine {
 my($hash) = shift;
 my($data) = $hash-{'expl'};
 
 print Content-type: text/html\n\n;
 print STOPHTML;
 div class=empdataThis employee has $data/div
 STOPHTML
 }
[...]
 I either get a 500 error or the $data string is not there as in the
 first instance of code. Can someone help?

Some notes on your code:

For once, you should not be writing my($variable) in an assignment unless you 
have understood its difference to writing my $variable.

To wit:

$ perl -wle 'my $data = localtime; print $data'
Mon Apr 12 11:25:22 2010
$ perl -wle 'my( $data ) = localtime; print $data'
28

Or as another example:

$ perl -wle 'sub foo { print wantarray ? List context : Scalar context } ; 
my( $data) = foo()'
List context
$ perl -wle 'sub foo { print wantarray ? List context : Scalar context } ; 
my $data = foo()'
Scalar context

= Using my() on the left side of an assignment creates a list context. There 
are functions like localtime that return different things depending on the 
context that they've been called from. Use my( $variable ) in an assignment 
only if you want to grab the first item of an array and discard all of the 
other data.

The other things is that you force extrapolation by saying $hash-{'expl'};. 
Not only is is superfluous in most instances, but it can hurt you, too, if the 
thing you're extrapolation isn't a string.

As for you initial problem, there's too little here to do an autopsy.

The list guidelines recommend that you post a minimal code sample that'll 
reproduce your problem.

Without access to that sample, I can only recommend that you run your code with 
use CGI::Carp qw/fatalsToBrowser/; to capture and print the error messages 
you're not seeing.

HTH,
Thomas





--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Date calculation help/suggestion please ... when there is no Date or Time module available

2010-04-08 Thread Thomas Bätzler
newbie01 perl newbie01.p...@gmail.com wrote:
 Problem 1:
 - Is there a function to compare the two (2) dates so ensure that I
 will always be doing future_date-past_date? At the moment, the
 workaround that am doing is if I get a negative value, then that
 means, I've done a past_date-future_date and need to change
 the way I print the output.

If you factor out the code that prints the output into a subroutine, then 
you're fine.

# pseudocode
if( $time_delta  0 ){
  print_subroutine( $t1, $t2, $delta );
} else {
  print_subroutine( $t2, $t1, -$delta );
}

That's actually much nicer than converting your timestamps to, say, time_t, 
then doing a compare and then probably exchanging them.

 Problem 2 is the bigger problem:
 - Now I want to use the same script to run on a UNIX box but
 unfortunately I do not have the Date::Calc module on that server.

You can basically build and install Perl modules in your home directory using 
normal user privileges - that way you would not mess up the system if that's 
what the sysadmin is afraid of. You can even hide that fact by using PAR / pp 
to bundle up your script, the Perl interpreter and all required modules in a 
single stand-alone binary that can be redistributed across machines if they're 
using the same OS release and architecture.

Of course, there still might be security concerns that prevent you from doing 
that. And if you want to build XS modules like Date::Calc you'll need the 
compiler/libs used to build your perl binary - at least in the good old days 
that meant that you had to have gcc installed.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: String length limits?

2010-04-08 Thread Thomas Bätzler
Hi,

Chris Coggins cacogg...@cox.net asked:
 Is there a limit to the length of a string in perl? I'm combining about
 200 pieces of data into a single string and writing the string to a
 file and am getting some weird behaviors every once in a while. Does perl
 have a limit on the length of a string it writes to a simple file?

In Perl, string size is limited to the amount of memory available to your 
process, which may be less than the amount of memory installed in your computer.

Care to elaborate on weird behavior for us?

Could it be a file systems problem, i.e. writing more than 4GB to a single file 
on a FAT32 filesystem?

Does the weirdness happen in the context of a web application? If yes, could it 
be a file locking issue?

If it's none of the above, did you run a memtest yet?

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: about beginner perl site and developing skill

2010-04-08 Thread Thomas Bätzler
 What is a CMS?

http://en.wikipedia.org/wiki/Content_management_system

 What is meant by chipcards?

http://en.wikipedia.org/wiki/Chip_card

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Perl: Subroutines and use of the GD::Graph::bars; Module

2010-04-07 Thread Thomas Bätzler
alekto alekto.antarct...@gmail.com asked:
 I manage to generate the array from the input file, but it seems like
 there is something wrong with my subroutine at the end, I have been
 using the examples at cpan.org as an templat for this subroutine.
 Following is the error msg, as well as the complete script.

 hostname$ ./bars.pl -f age
 ./bars.pl: line 5: use: command not found
 Array found where operator expected at ./bars.pl line 90, at end of
 line
   (Might be a runaway multi-line // string starting on line 53)

And the winner is...

printHistogram(/@array,$filename,$histmin,$histmax,'Age');

Use \ instead of / to create a reference.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Converting 12 hour time format to 24 hour format ... a bit urgent

2010-04-07 Thread Thomas Bätzler
newbie01 perl newbie01.p...@gmail.com asked:
 Unfortunately, I suddenly have to to deal with an input file where the
 datetime format is 02-Apr-2010 3:41:23 p.m., i.e. DD-MON- HH:MI:SS
 a.m./p.m., so now my Delta_YMDHMS does not work as expected.

You can convert from a.m./p.m. to standard 24 hours using a simple RE:

#!/usr/bin/perl -w

use strict;

while( my $line = DATA ){
  $line =~ s/(\d+)(:\d+:\d+)\s+(a|p)\.m\./($3 eq 
'a')?($1%12).$2:($1%12+12).$2/e;
  print $line;
}

__DATA__
02-Apr-2010 12:41:23 a.m.
02-Apr-2010 12:41:23 p.m.
02-Apr-2010 3:41:23 a.m.
02-Apr-2010 3:41:23 p.m.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: about the various styles of `open'

2010-04-06 Thread Thomas Bätzler
Harry Putnam rea...@newsguy.com asked:
 I see advanced users here using various styles of open().

[three argument open]

 Is there something beyond style that makes those methods better than
 what appears to be a simpler format:

[two argument open]

Allow me to quote perldoc -f open:

  The filename passed to 2-argument (or 1-argument) form of open() 
will have leading and trailing whitespace deleted, and the normal redirection 
characters honored.  This property, known as magic open, can often be used to 
good effect.  A user could specify a filename of rsh cat file |, or you could 
change certain filenames as needed:

   $filename =~ s/(.*\.gz)\s*$/gzip -dc  $1|/;
   open(FH, $filename) or die Can't open $filename: $!;

   Use 3-argument form to open a file with arbitrary weird 
characters in it,

   open(FOO, '', $file);

   otherwise it's necessary to protect any leading and trailing 
whitespace:

   $file =~ s#^(\s)#./$1#;
   open(FOO,  $file\0);

   (this may not work on some bizarre filesystems).  One should 
conscientiously choose between the magic and 3-arguments form of open():

   open IN, $ARGV[0];

   will allow the user to specify an argument of the form rsh cat 
file |, but will not work on a filename which happens to have a trailing 
space, while

   open IN, '', $ARGV[0];

   will have exactly the opposite restrictions.

I hope this answers your question ;-)

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Working with files of different character encodings

2010-04-06 Thread Thomas Bätzler
Doug Cacialli doug.cacia...@gmail.com asked:
 Does anyone have any ideas how I can make the second block of code
 work?  Or otherwise accomplish the task without opening the .txt file
 twice?

How large are your data files? If your available memory is much larger than 
your maximum file size, you might get away with slurping the file into a scalar 
and then convert its encoding if needed, possibly like this:

#!/usr/bin/perl -w

use strict;
use Encode;

my $file = 'test.txt';

open( my $fh, '', $file ) or die Can't open '$file': $!;

my $data = do {
  local $/ = undef;
  $fh;
};

close( $fh );

if( $data =~ m/^\xff\xfe/ || $data =~ m/^\xfe\xff/ ){
  print input is UTF-16 w/ BOM\n;
  $data = decode('utf-16',$data);
} elsif( $data =~ m/^[^\x00]\x00/ ){
  print input is probably little-endian utf-16 w/o BOM\n;
  $data = \xff\xfe . $data;
  $data = decode('utf-16',$data);
} elsif( $data =~ m/^\x00[^\x00]/ ){
  print input is probably big-endian utf-16 w/o BOM\n;
  $data = \xfe\xff . $data;
  $data = decode('utf-16',$data);
}

chomp( $data);

my @words = split /\s+/, $data;

print input file has . scalar( @words ) .  words\n;

__END__

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Perl appears to be introducing whitespace when reading .txt files

2010-04-01 Thread Thomas Bätzler
Doug Cacialli doug.cacia...@gmail.com wrote:
 The unicode / UTF16 issues presented by Thomas and Dr. Rudd are a
 little beyond me.  I'm reading up now, but can someone shed some
 light?

Let's see if I can quickly summarize:
- text is made up from letters (characters).
- a computer doesn't know letters, it only knows numbers (bytes).
- an encoding specifies how letters are mapped onto numbers. In classic ASCII 
encoding, the byte value 65 represents the character A.
- For a long time, the most common encodings where single-byte encodings that 
basically could represent up to 256 different characters.
- There are also multi-byte encodings that can encode many more characters. One 
of those is Unicode which endeavours to be the one ring of character 
encodings.
- There are several storage formats for Unicode. One of those is UTF-16, which 
encodes most of what we'd consider common characters in two bytes each, while 
using 4 bytes for the rest.
- One of the big problem with plain text files is that there's usually no hint 
as to their encoding.

So what we assume is happening is that your data is stored as UTF-16, where 
standard ASCII characters are stored as two bytes of data.

Your program doesn't specify that the data is UTF-16, so perl reads it as 
single-byte encoded data, effectively introducing lots of null characters 
into the string.

You now have two options: either convert your input, or modify your program to 
handle Unicode input.

In any case you could try this snipped in your code:
print NUL character found in string - input might be UTF-16\n if $line =~ 
m/\x00/;


MfG,
Thomas Bätzler
-- 
BRINGE Informationstechnik GmbH
Zur Seeplatte 12
D-76228 Karlsruhe
Germany

Fon: +49 721 94246-0
Fon: +49 171 5438457
Fax: +49 721 94246-66
Web: http://www.bringe.de/

Geschäftsführer: Dipl.-Ing. (FH) Martin Bringe
Ust.Id: DE812936645, HRB 108943 Mannheim



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Syntax of Foreach loop

2010-03-31 Thread Thomas Bätzler
Jon Forsyth jon4s...@gmail.com asked:
 I am truly a beginner.  Could someone help me understand this syntax
 out of a code example from Learning Perl?  On line 5 I'm confused
 as to why my $number is between foreach and the ()?  is my
 $number part of the loop?

my declares a variable for the lexical scope. While Perl by itself will 
happily let variables spring into existence whenever you first refer to them, 
the accepted best practice is to run perl with the -w switch or the use 
warnings; pragma which requires variables to be declared before their first 
use.

The foreach loop iterates over each element in the argument list passed 
between the (). Unless there's a variable name between the keyword foreach and 
the braces, foreach makes the default variable $_ to an alias for each of the 
elements in the argument list. If there's a variable between foreach and the 
braces, that variable becomes the alias instead.

Please note that I said alias instead of copy - if you modify $_ or your loop 
variable, it'll change the contents of your array:

#!/usr/bin/perl -w

my @array = qw(foo baz bar);
print join(',',@array), \n;

foreach (@array){
  $_ = uc($_);
}

print join(',',@array), \n;
__END__

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: AW: Syntax of Foreach loop

2010-03-31 Thread Thomas Bätzler
Uri Guttman u...@stemsystems.com wrote:


  TB == Thomas Bätzler t.baetz...@bringe.com writes:


   TB with the -w switch or the use warnings; pragma which requires
   TB variables to be declared before their first use.
 
 that is the use strict pragma, not the warnings one.

Of course. I knew I shouldn't have posted before my first cup o' coffee ;-)

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Perl appears to be introducing whitespace when reading .txt files

2010-03-31 Thread Thomas Bätzler
Doug Cacialli doug.cacia...@gmail.com wrote:
 I'm completely baffled by this and not entirely sure where to start.
 
 I have a plain text  file, testfile.txt, which contains a single line:

Could this be an encoding issue? How big is that file? Larger than 18 or 19 
bytes? 

If yes, http://perldoc.perl.org/perlunicode.html#When-Unicode-Does-Not-Happen 
may have the answer.

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Storing a Hash Inside An Array

2010-03-26 Thread Thomas Bätzler
Pry, Jeffrey jeffrey@sig.com asked:
 Now, I was wondering if it would be possible to store a hash inside of
 an array.

Sure, just use the anonymous hash constructor {}, i.e. like

  $settings[$i] = { 'ftpserver' = localhost, 'password' = 'p...@$$word' };

Or add/change individual keys in the hash

  $settings[$i]-{ 'username' } = 'anonymous';

Or store the hash inside a hash

  my %host_settings = (
'localhost' = { 'password' = 'p...@$$word' },
'ftp.cdrom.com' = { 'username' = anonymous, password = 'w...@r.es' },
  );

Then you could say

  my $host = 'ftp.cdrom.com';

  print Known settings for $host:\n

  foreach my $parameter ( keys %{ $host_settings{ $host } } ){
print  - $parameter:  . $host_settings{ $host }-{ $parameter } . \n;
  }

Or store a hash inside an array inside a hash inside an array...

  push @slightly_silly_example, { 'key' = [ { 'some' = 'text' } ] };

Whatever you're doing, go check out Data::Dumper. It's invaluable when you're 
hitting a snag working with nested data structures.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Regex question

2010-03-24 Thread Thomas Bätzler
Bruce Ferrell bferr...@baywinds.org wrote:
  if ( ! defined $username || ! $username =~ /[0-9]{10,11}/ ) {
 
 do something;
 
 } else {
 
 do something else;
 
 }
 
 what that's supposed to do is this:
 if it's blank or not 10 or 11 digits...
 
 The question is where is my understanding faulty or did I mess up.

defined() is true if the checked variable has been assigned any value except 
undef, so defined $username will be true for an empty username, too.

In any case I'd probably rather write your code like this:

$username ||= ''; # make sure it's always defined

unless( $username =~ m/^\d{10,11}$/ ){
  # bad username
} else {
  # good username
}

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Deleting last 10 lines of a file

2010-03-23 Thread Thomas Bätzler
sheela b sheela.b.2...@gmail.com asked:
 How to delete last 10 lines of a file using Perl one liner?
 
 I used the following one liner to delete first 10 lines of a file,
 
 perl -i.bak -ne 'print unless 1..10' test.txt

OTTOH:

perl -i.bak -ne 'BEGIN { $b[9]= } print shift @b; push @b, $_' 
test.txt

@b is the bucket chain of 10 initially empty strings. Inside the implied 
while() loop, new text is added at the end of the chain while the head element 
is pruned and then printed. The loop will terminate on eof(), leaving the last 
10 lines of text in the array.

If you're dealing with small files, another option would be to slurp in the 
file to an array, delete the last 10 items of the array and write the file back 
out to disk.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: CGI-BIN Help/Advise - editing a file - HOW ?

2010-03-15 Thread Thomas Bätzler
newbie01 perl newbie01.p...@gmail.com asked:
 At the moment, I have some sort of INI/config file that I edit manually
 via vi. These config files are simple delimited file that are used by
 some of the scripts running on the server.
 
 I want to be able to the same thing via cgi-bin, can anyone advise where
 to start. Basically, I want to be able to display the contents of the
 INI/config file in some kind of FORM or web page and then allow the user
 to be able to edit and save it at the same time.
 
 Any advise on where to start will be very much appreciated. Am not sure
 if I should be using PHP instead of CGI-BIN but I thought the latter
 would be simpler to do.
 
 Being able to prompt for a username/password prior to editing the file
 would be a plus ... :-)

If I may start with the last question: user authorization is usually easiest 
handled as part of the web server configuration. If you're using Apache, look 
at the Location directive.

Also, there's no programming language called CGI-BIN. CGI is a calling 
convention that defines how the web server invokes external programs to handle 
calls to certain URLs. Since CGI usually involves starting a new process for 
the external program it's less effective for either Perl or PHP than using a 
built-in interpreter in the web server. In PHP the latter is often called using 
SAPI while Perl people talk about using mod_perl.

Solving your problem is possible in either language. Since this is a Perl list, 
we'll stick to using Perl here, though.

At this point you'll probably want to look at the CGI module for all of your 
page rendering and argument parsing needs.

Your code flow will likely look something like this:

1) Read config file into memory
2) Apply changes submitted by the user to the in-memory representation
3) Render the in-memory representation to a form where the user can edit values
4) Write out the config file data if it was changed

Things to keep in mind are

- You might want to do implement some kind of locking to prevent two people 
from editing your file ant once, since this may lead to lost updates (where 
changes from one user overwrite the changes previously submitted by another 
user) or worse (a trashed output file).

- Pressing the stop button in the browser can cause your program to abort in 
mid-execution. You'll want to make sure that this doesn't happen while handling 
the update of the output file.

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Please excuse the NOOB question - but I guess since this is a perl.beginners group

2010-02-26 Thread Thomas Bätzler
Hi,

GlenM glenmill...@gmail.com wrote:
 I am sure that someone out there has done this before - I *think* I am
 on the right track.
 
 I have a directory full of emails. What I would like to do is read
 each file in, then parse them into a CSV style file.

Quick aside: you can use the $. builtin variable to get the line number instead 
of keeping track of it yourself.

Since you asked for suggestions, here's my $0.02:

Putting mails line by line into a CSV files seems futile to me, since the 
number and position of mail headers is variable.

If you want to create a database of your mails or do some other sort of data 
mining I would suggest that you look at something like the MIME-Tools bundle[1] 
to do the actual parsing and the concentrate on doing something useful with the 
extracted information.

HTH,
Thomas

1) http://search.cpan.org/~doneill/MIME-tools-5.427/lib/MIME/Tools.pm


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: newline problem

2010-02-01 Thread Thomas Bätzler
Michom michel.makhlo...@gmail.com asked:
 I am new to perl and I have written a smal script to grab data from
 one file, and put them into another file. The problem is new lines,
 which are printing nice under a linux environment, but it is all
 messed up if I open it with notepad. I am running Perl 5 under cygwin.

This is a feature of Notepad - it expects DOS-style \r\n as a line ending.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Warning: Use of uninitialized value

2010-01-28 Thread Thomas Bätzler
Bob Williams n...@spam.barrowhillfarm.org.uk asked:
 I am trying to split the lines in a file into two halves (at the first
 space) each half going into an array. The code I have written is below.

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

use strict; # unless you know what you're doing.

 #use diagnostics;
 
 # perl script to compare two files of md5 checksums
 #+and extract the lines which differ
 
 open (BHF_FILE, /home/bob/tmp/md5music)
   or die Could not open md5music: $!;

Better:

open( my $bfh_file, '', '/home/bob/tmp/md5music' ) or die ...

 @bhffile = BHF_FILE;
 close (BHF_FILE);
 
 for (my $i = 0; $i = $#bhffile; $i++){
   $bhffile[$i] =~ m/(\s.+) ( .+)/;
   push @ukchecksum, $1[$i];
   push @uktrackname, $2[$i];
 }

If your track names are unique, you're much better off using an associative 
array (hash) for your data.

It also makes comparison with track names and checksums from a second list much 
easier:

my %uktrackchecksum;

while( my $line = $bhf_file ){
  my( $track, $checksum ) = split /\s+/, $line;
  $uktrackchecksum{ $track } = $checksum;
}

close( $bhf_file );

 print @ukchecksum[0]; # Won't print - uninitialized value ???
 print @uktrackname[0];# Won't print - uninitialized value !!!

foreach my $track (keys %uktrackchecksum){
  print $track = $uktrackchecksum{ $track }\n;
}

HTH,
Thomas

PS: Totally OTTOH, please excuse any typos.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: passing a hash via cookie and dereferencing it

2010-01-19 Thread Thomas Bätzler
mike msmspellman...@gmail.com asked:
 I am trying to pass a hash of hashes from one script to another via a
 cookie.  I can get the cookie to pass, but when I try to get the inner
 hash keys and values using what I think is the correct method, I
 cannot get them.  Here are two scripts which should do it, but don't:

Assuming that you do traditional CGI, each script invocation starts a new Perl 
process that exists after executing the script. When that happens, all your 
data is expunged and the hash reference you passed becomes invalid.

What you want to do is called session handling and there are oodles of modules 
for doing that on CPAN.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: chroot as non-root?

2010-01-04 Thread Thomas Bätzler
Trevor Vallender t...@tsv.me.uk asked:
 I am designing a system in which scripts are installed into their own
 directory, by a non-root user, under their home directory.
 
 It is very important they not be allowed to write anywhere outside the
 directory they are installed in. There are two ways I thought of doing
 this; create a user for each script to run as, without permission to see
 outside of its directory, or run in a chroot.
 
 My problem here is both of these methods need root privileges to get
 started, and for the life of me I cannot think how to get around this.
 Is there any way at all to create a chroot-like environment without root
 privileges?

You don't mention on which OS you're trying to implement this, but if it's 
Linux, then maybe SELinux (http://selinuxproject.org/page/Main_Page) might be a 
solution for you.

When I had similar requirements in the past, I've always opted for a 
chroot-based solution, though - mainly because I knew I could make it work with 
limited effort.

What I'd do is run a ssh daemon in a chroot jail and then make my unprivileged 
users connect to that instead of the real system.

HTH,
Thomas


AW: :POP3 -- download only x number of mails

2009-12-13 Thread Thomas Bätzler
Agnello George agnello.dso...@gmail.com asked:
 I am planning to use the Net::POP3 module to downald a mail box and then
 pass the mails via a parser . I would like to know if the there is a
 option to downlod only  a  certin number ( 100 )  of mails [unread]
 and  then mark the mails as read  . The mail box sie is 400 mb . And is
 there a way to keep the mails on the server.

You can do the first two things without a problem. The third depends on the 
POP3 server's setup. Read mail may be expunged from the mailbox regardless of 
whether you requested it to be deleted or not.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: how to automate yum installation

2009-12-07 Thread Thomas Bätzler
mahesh bhasme mbha...@gmail.com asked:
 I want  to  pass yes/no argument to this comment : (Is this ok [y/N]: [y]
 )
 . How we can do this in perl?

Generally speaking, read the perlipc manpage (perldoc perlipc on the command 
line).

In this particular instance, I'd rather suggest using yum -y instead.

MfG,
Thomas Bätzler
-- 
BRINGE Informationstechnik GmbH
Zur Seeplatte 12
D-76228 Karlsruhe
Germany

Fon: +49 721 94246-0
Fon: +49 171 5438457
Fax: +49 721 94246-66
Web: http://www.bringe.de/

Geschäftsführer: Dipl.-Ing. (FH) Martin Bringe
Ust.Id: DE812936645, HRB 108943 Mannheim





--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Regular expressions question

2009-11-18 Thread Thomas Bätzler
Hi,

Dermot paik...@googlemail.com suggested:
 2009/11/17 mangled...@yahoo.com mangled...@yahoo.com:

  Can anyone tell me hoq to write a regular expression which matches
  anything _except_ a litteral string ?
 
  For instance, I want to match any line which does not begin with
  Nomatch.  So in the following :


 You would negate the pattern. Something like this:
 
 #!/usr/bin/perl
 
 
 use strict;
 use warnings;
 
 while (DATA) {
 print if ! /^Nomatch/;
 }
 
 __DATA__
 Line1 
 Line2 
 Nomatch 
 Line3 
 Line 4 

One could also use a zero-with negative look-ahead assertion:

#!/usr/bin/perl -w

use strict;

while( my $line = DATA ){
  if( $line =~ m/^(?!Nomatch)/ ){
print match: $line;
  }
}

__DATA__
Line1 
Line2 
Nomatch 
Line3 
Line 4 

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Perl CGI Incremental find

2009-11-17 Thread Thomas Bätzler
Hi,

Jeff Pang pa...@uk2.net wrote:
 On Nov 17, 2009, Dave Tang d.t...@imb.uq.edu.au wrote:
  Is it possible to implement an incremental find* feature on a Perl CGI
  page? I'm running Apache2 with mod_perl on linux.
   
  For example, if I have a list of stuff (A, Aa, B, Bb, C, CA, etc. stored
  in a file or database) and when a user starts typing in A into the web
  form, 2 suggestions in a drop down menu will come up (A and Aa but not
  CA). Users will be able to click on this drop down menu and the web form
  will be filled with what they clicked on. A real life example would be
  Google Suggest**.

 This is the stuff JavaScript will do, nothing about CGI, which is a 
 server-end implement.

Yes and no. What the OP is inquiring about is a combination of technologies 
that are usually referred to as AJAX[1]. One possible starting point would be 
CGI::AJAX[2]. 

HTH,
Thomas

[1] http://en.wikipedia.org/wiki/Ajax_(programming)
[2] http://search.cpan.org/~bpederse/CGI-Ajax-0.707/lib/CGI/Ajax.pm


AW: foreach loop

2009-11-02 Thread Thomas Bätzler
Anant Gupta mailto:anantgupta...@gmail.com asked:
 In the foreach loop, without going to the beginning of the loop, i want
 to get the next iteration of data. How do i get it.

You should probably not slurp (read in all at once) the file unless you need 
to.

In your particular case reading in line by line is especially useful since this 
would allow you to retrieve the next line from the file handle without having 
to go to the next iteration in the loop.

Eg. (untested  OTTOH though):

my $filename = 'abc.txt';

open( my $file, '', $filename ) or die Can't open '$filename': $!;

while( my $line = $file ){
  if($line =~ m/something/){
if( defined( $line = $file ) ){
  # do something with new line
} else {
  # handle EOF here
}
  }
}


HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: foreach loop

2009-11-02 Thread Thomas Bätzler
Philip Potter philip.g.pot...@gmail.com asked:
 Won't this loop terminate early if there is a blank line or a line
 containing only '0'? If I do a readline loop I always do:
 while (defined ($line = $file))
 
 Is there something magical happening here I don't know about? I know
 about the magical:
 
 while ($file)
 
 which is equivalent to:
 
 while (defined($_ = $file))
 
 but I don't know of any magic in the while loop at the top.

See the Camel book, p.81:

[...]

   while( my $line = STDIN ) { print $line; } # now private

Both of these while loops still implicitly test for whether the result of the 
assignment is defined, [...]

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: How do I pick one random element from an array?

2009-11-02 Thread Thomas Bätzler

Majian jian...@gmail.com asked:
[...]
 print Array of random: $array[rand @array]\n;
 
 
 I thoght it might work but it doesnt. I hope someone could give me an
 idea to work this out...

TIMTOWTDY:

a) print Array of random: $array[rand( @array ) ] \n;

b) print Array of random:  . $array[rand @array] . \n;

c) my $random_name = $array[rand @array];
print Array of random: $random_name\n;

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: AW: How do I pick one random element from an array?

2009-11-02 Thread Thomas Bätzler
Dave Tang d.t...@imb.uq.edu.au asked:
 Just a quick question, how does Perl interpret something like
 $array[0.7995038473872]?

Just like $array[ int(0.7995038473872) ], i.e. the floating point number is 
coerced into an integer value by cutting off the decimal places.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: About the hash case insensitive ~~~

2009-10-27 Thread Thomas Bätzler
Majian jian...@gmail.com asked:


 %courses = (
  2CPR2B= C Language,
  1UNX1B= Intro to Unix,
  3SH414= Shell Programming,
  4PL400=  Perl Programming,
 );
 
 print \n\EDP\ NUMBERS AND ELECTIVES:\n;
 while (($num, $value) = each (%courses))
 {
 print -\n;
 printf %-10s | %s\n , $num, $value;
 }
 
 print \nWhat is the EOP number of the course you wish to take : $num;
 chomp ($num = STDIN);
 print The course you will be taking is: \$courses{$num}\\n;
 ===
 The question was :
 
 If I type  the 4PL400,  then it will output the value ---Perl
 Programming;
 But I want to type the 4pl400 , and the result should be printed Perl
 Programming
 
 How could I  come it  true?

Use chomp ($num = uc(STDIN) ) to uppercase the input and make sure that all 
your keys are in upper case, too.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Building a fmt line for printf with a carriage return

2009-10-26 Thread Thomas Bätzler
Hi,

Wagner, David --- Senior Programmer Analyst --- CFS david.wag...@fedex.com 
wrote:
   Here is the sample script I was playing with:
 #!/usr/bin/perl
 
 use strict;
 use warnings;
 
 my $MyLine1 = q[%2d  %5s  %6s];
 my $MyLine2 = q[%2d  %5s \n%6s];

The q// operator is equivalent to single quotes, so escape sequences like \n 
are not interpolated.

If you want \n to be expanded to a newline character, you need to use qq or 
double quotes, or a combination of q// and qq// or quotes and text 
concatenation.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: perl document

2009-10-26 Thread Thomas Bätzler
mahesh bhasme mbha...@gmail.com asked:
 I am new to perl. From where I get the basic perl document

Depends on your distribution, really. If you're on Windows and using the 
ActiveState Perl distribution, look for the html folder in your Perl 
installation directory.

On Unix, you might want to try perldoc or man to get you started. Have a look 
at the perlsyn, perlop and perlrun documents (perldoc persyn etc) if you've 
got some programming experience.

If you don't, you might be better off with supplementary documentation in book 
form like Learning Perl - please see http://books.perl.org/.

HTH,
Thomas



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: compact my wordlist generator

2009-10-26 Thread Thomas Bätzler
Michael Alipio daem0n...@yahoo.com wrote:
 Can anyone tell me how the code above works? My original program must
 deal with arbitrary length and generate all the possible combinations
 (even repeating) of a particular set. What could take me gazillions of
 for loops for that, somebody just came up with less than ten lines.
 I can just copy and paste the code I found above but I want to learn how
 it works. How could someone write this code so easily but when I tried
 even writing just a pseudocode for it, my head almost exploded.

It probably helps if you have some understanding of the underlying mathematics 
of the problem domain, i.e. in this case combinatorics.

This would also clear up potential misunderstandings viz the definition of a 
permutation (randomly pick n of m elements without putting them back) vs. 
that of a combination (randomly pick n of m elements while putting them back).

 I want to be a good programmer, but at this rate, I don't think I can be
 one if I will just keep copying and pasting someone else's code or
 downloading modules from CPAN.

Actually, taking somebody else's code and trying to figure out how it works is 
a good exercise ;-)
 
 Can anyone teach me how my own code (the one with gazillion for loops),
 can be converted into a pseudocode then eventually into a working sub
 procedure?

No, probably not right away. But the good news is that most people don't come 
up with elegant solutions off the top of their heads - instead, they will have 
learned a number of basic patterns and/or algorithms for solving common 
problems, and they will have the experience to adapt what they know to new 
problems.

So, in order to become a better programmer you should look at stuff people have 
been doing before you. Go to your local library and borrow a book on 
Algorithms. Try to implement them in Perl. Have a look at the Perl cookbook. If 
you want a challenge, then treat yourself to a copy of Higher Order Perl by 
Mark Jason Dominus.

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: AW: compact my wordlist generator

2009-10-26 Thread Thomas Bätzler
Michael Alipio daem0n...@yahoo.com wrote:
 I knew I needed a recursive function, I just didn't know how to start.

That is usually the easy part - you start out by solving the problem for a base 
case, and then you embellish.

With regard to your problem of generating all combinations of a set of 
elements, the base case would be to just enumerate those elements.

For a longer result set with n elements (n being  1), you'd then combine the 
result for n-1 elements with the one element result set.
 What confused me more is that the code I found is a lot different from
 what I was initially thinking. He used the builtin function substr in the
 code in a way that I couldn't figure how it worked.

If in doubt, it pays off to RTFM ;-)

So you do perldoc -f substr and it'll tell you:

  You can use the substr() function as an lvalue, in which case EXPR must 
itself be an lvalue.

It helps to know that lvalue is short for left-hand value and it basically 
means that it behaves like a variable on the left hand side of the assignment 
operator - it can be assigned a value.

The example from the man page helps to clarify this behavior:

  my $name = 'fred';
  substr($name, 4) = 'dy'; # $name is now 'freddy'

 What's the use of double ($$) after sub perm?? Does it have anything to
 do with process IDs (perldoc perlvar says so)?

Nope, these are prototypes for the function call (see perldoc perlsub, section 
Prototype). Basically these two $$ signs make the function request two 
arguments, which will be coerced to scalar values. This is of course only half 
the truth, but I'll leave the nasty details and consequences to more erudite 
folks on this list to explain ;-)

 This line is also confusing:
 substr($result,$cur,1)= $_;
 
 Substr returns a list, right? The first parameter is the expression, 2nd
 is the offset, and last is the length.
 The above line is too cryptic for me. What confused me more is that the
 return value of substr was assigned the $_.

Actually, substr() as an lvalue designates a part of the string $result that 
will be assigned to, but please see above.

BTW, taking the recursive approach outlined above and using Iterators, my first 
draft for a combination generator looks like this:

#!/usr/bin/perl -w

use strict;

#
# Iterator that generates all combinations of length $n of a set of elements.
#

sub gen_combo_iterator {
  my( $n, @elements ) = @_;

  # base case: iterator for all one element combinations
  # This will just enumerate all elements of the set
  
  if( $n == 1 ){
  
# this is a so-called closure - we return an anonymous subroutine that
# can still access the variables in its outer scope even though they
# are no longer visible for the rest of the program.

# subsequent calls to the anonymous function will manipulate a copy
# of the variable @elements that was created when the function was
# created by calling the outer subroutine.
  
return sub {
  return shift @elements;
};

  } elsif( $n  1 ){
  
# recursion: all combinations of n elements are the product
# of all (n-1) element combinations x all 1 element combinations.

# this call with fall through until it reaches $n = 1
my $sub_combo_iterator = gen_combo_iterator( $n -1 = @elements );

# the second iterator has just one element
my $combo_iterator = gen_combo_iterator( 1 = @elements );

# we pick the first element
my $element = $combo_iterator-();
  
return sub {

  if( my $sub_combo = $sub_combo_iterator-() ){
# if the iterator over all combinations of length n-1 still
# returns a value, combine it with my current item.
return $element . $sub_combo;
  } else {
  
# try and pick a new element from the 1 element iterator
if( $element = $combo_iterator-() ){

  # if there's a new element, reset the n-1 element iterator  
  $sub_combo_iterator = gen_combo_iterator( $n -1 = @elements );
  
  # get a fresh element from the n-1 element iterator
  $sub_combo = $sub_combo_iterator-();
  
  # combine with the current element and return like above
  return $element . $sub_combo;
} else {
  # nothing more to return, we are finished.
  return undef;
}
  }
};

  } else {
die Assertion: $n must be a positive inter greater or equal 1;
  }  
}


#
# generate an iterator that will return all combinations of a given set
# with $min up to $max elements.
#

sub gen_all_combinations_iterator {
  my( $min, $max, @elements ) = @_;
  
  if( $min  $max ){
  
my $iterator = gen_combo_iterator( $min = @elements );

return sub {
  if( my $result = $iterator-() ){
return $result;
  } else {
$min++;
if( $min = $max ){
  $iterator = gen_combo_iterator( $min = @elements );
  return $iterator-();
} else {
   

AW: Url written in txtfile

2009-10-05 Thread Thomas Bätzler
Hi,

Ruprecht Helms rhe...@rheynmail.de asked:
 actually I have written the following line:

Currently. actually is actually a false friend.

 print STATISTIKDATA
 CGI-a({href='http://www.b-net-
 c.de/adressbuch/$Vorname_$Name_$id.html'},'Link
 zum Profil');

You are using the wrong quote marks. Use double quotes if you want variable 
names in the string to be replaced by their values.

That'll raise the next problem, though: _ is a valid character for a variable 
name, so the Perl interpreter will try to access the variable $Vorname_ which 
probably isn't what you wanted. In such a case, use curly braces to delimit the 
variable name, like this:

print STATISTIKDATA 
CGI-a({href=http://www.b-net-c.de/adressbuch/${Vorname}_${Name}_$id.html'},'Link
 zum Profil');

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Url written in txtfile

2009-10-02 Thread Thomas Bätzler
Ruprecht Helms rhe...@rheynmail.de asked:
 how have I to write the printstatement to write a URL like
 http://www.example.com within the htmltag (a
 href=http://www.example.com;Linktext/a) into a textfile.

Hm, for example

#!/usr/bin/perl -w

use strict;

my $file = '/some/path.txt';

my $text = 'a href=http://www.example.com;Linktext/a';

# naïve url extraction example. See mailing list archive for
# proper solution(s) of how to do this using a parser.
my( $url ) = ($text =~ m{a href=(.*?)});

open( my $fh, '', $file ) or die Can't open '$file': $!;

print $fh $url\n;

close( $fh )

__END__

OTTH  YMMV of course.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Hash of Hashes

2009-09-29 Thread Thomas Bätzler
Soham Das soham...@yahoo.co.in asked:
 How can I create a Hash of Hashes from two lists. Is it possible?
 
 I want the effective functionality to be served like this
 
 $ChildHash[Joe][21A]=Sally
 
 i.e Joe at 21A has a child called Sally. List1 here will be the name of
 Parents, List2 here will contain the house number.

Please keep in mind: square brackets are for arrays/lists. Curly brackets are 
for hashes.

In any case, wouldn't it be smarter to organize your data differently?

I.e.:

%parent = ( 'Joe' = { 'address' = '21A', children = ['Dick','Sally'] } );

To add another child to an existing parent you'd then say

push @{$parent{'Joe'}{'children'}}, 'Jane';

To add a new parent:

@{$parent{'Sven'}}{'address','children'} = ( '9b', ['Bjorn'] );

HTH,
Thomas


AW: Burnt Camel Club

2009-09-22 Thread Thomas Bätzler
Ian pcs...@gmail.com wrote:
 Keep it up and the hollier-than-though's will have the list to themselves
 eventually.

What's holly got to do with it, though? ;-)

SCNR,
Thomas ;-)

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: CGI and persistent data (without Storable)

2009-08-28 Thread Thomas Bätzler
Steve Bertrand st...@ibctech.ca asked:
 I'm writing a web interface using CGI::Application for a project that
 houses numerous methods within a dozen modules.
 
 One particular process displays a template to the user with passed in
 data, and then has four more steps before completing. The result of this
 procedure will be the modification of an elaborate data structure. The
 data structure may need to be modified along the way.
 
 Given that I can get through the web GUI portion of the process with
 just a couple of params, I'd like to find a way to retain the entire
 data structure without having to re-instantiate it (which requires
 rebuilding numerous objects etc), or pass each variable within it as a
 param on each CGI invocation.
 
 Can I, and is it plausible to create a cyclic ref redundancy of the data
 structure, store the memory location in a variable, pass the variable
 data as a param, and then recreate the data based on the variable that
 contains the memory location at the end of the entire CGI process? Is
 exploiting Perl's garbage collection like this possible, and ok to do?
 
 I'd like to be able to 'carry' the data structure without having to
 'store' it to disk, if possible

If you're using standard Perl CGI, a new interpreter is spawned for each of 
your requests. At the end of each request, the interpreter exists, and it takes 
any uncollected garbage with it. The next Perl process you start will get a 
completely new, empty, pristine memory space without any traces of previous 
use. So you can't store store data in memory between invocations that way.

The easiest way to have persistent data across invocations is having a 
persistent Perl process and session handling. With CGI, this means using Apache 
and mod_perl and possibly a toolkit/framework/whatchamaycallit like Embperl on 
top. Although I have not used it yet personally, I would assume that the jifty 
framework is up to the task, too.

If you can't use mod_perl or a stand-alone jifty server and if you have a Unix 
system, http://search.cpan.org/~samtregar/IPC-SharedCache-1.3/SharedCache.pm 
might be useful.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: How to pass info to a CGI program without using a form?

2009-08-24 Thread Thomas Bätzler
Disclaimer: I haven't written Perl or a major book on it so this answer is 
strictly IMHO, OTTOH and of course YMMV ;-P

boll b...@sonic.net asked:
 I would like to use this program in several places to display images
 from other directories, so that one URL might display a random image
 from the 'vegetables' directory, and a different URL would call the
 same program but display an image from the 'fruits' directory.

You can tack on so-called GET parameters to an URL by adding pairs of
?key1=value1 [ key2=value2 ... [ keyn=valuen ] ] 

Keys and values have to use a special encoding scheme for certain
special characters, see for example 
http://en.wikipedia.org/wiki/Percent-encoding

In your code, you can query these parameters using the param() method of
CGI.pm, like this:

my $q = new CGI;

my $key1 = $q-param('key1');

Keep in mind that people might call your script without a parameter or that 
they might try to hand-craft a value in order to exploit your code, so always 
validate your input and always provide a sane default value.

For example if you had a parameter like image category, you'd probably only 
want to allow numbers and lower case letters:

# make sure that your CGI parameter is clean
my( $img_category ) = ( $q-param('category') =~ m/^([a-z0-9]+)$/ );

# default for bad/missing parameter
$img_category ||= 'flowers';

Selecting the image based on a given category is left as an exercise for the 
reader. Hint: you might  want to extend the format of the image file list to 
include a category column.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Trying to remove text in inverted commas.

2009-08-24 Thread Thomas Bätzler
Hello Gregory,

Gregory Machin gregory.mac...@gmail.com asked:
 I'm writing a script to import logs into a Mysql .. My Perl is rusty
 and I'm battling with a convention on the one column.  I need to
 remove the text in inverted commas  Prashil 106 so that just the
 number 106 remains.. I have been trying the following regex
 s/(\([^]+)\\s)//g but it doesn't seem to work. 

It's always helpful if we can see several lines of sample input aswell as the 
output you wish to achieve so that we can understand your problem better. If 
your code doesn't work, please post the relevant portion of it.

The RE you quoted will match a substring consisting of a double quote, followed 
by at least one character that is not a double quote, followed by another 
double quote and finally a whitespace (blank, tab) character. The match will be 
removed sicne you replace it with an empty string. Due to the modifier /g it 
will do that to multiple instances of the match in one line.




AW: WELCOME to beginners@perl.org

2009-08-21 Thread Thomas Bätzler
Ajay Kumar aku...@securities.com asked:
 Gesendet: Freitag, 21. August 2009 12:23
 An: beginners@perl.org
 Betreff: RE: WELCOME to beginners@perl.org
 
  Hi All
 
 I have great issues
 
 1) perl -e '$a=0.123451005;$a=sprintf(%.8f,$a);print=$a\n;'
 Output=0.12345101
 2) perl -e '$a=5.123451005;$a=sprintf(%.8f,$a);print=$a\n;'
 Output=5.12345100
 
 
 Here 1 one ging correct result but the second one wrong result
 For second one result should be 5.12345101 but it is giving 5.12345100
 
 
 May I know  why it behabe So

See the first question in the Data: Number section of 
http://perldoc.perl.org/perlfaq4.html 

For the gritty details, see the article 
http://en.wikipedia.org/wiki/Floating_point and especially its setion 
representable numbers at Wikipedia.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: fast installing modules

2009-08-18 Thread Thomas Bätzler
Jenn G. practicalp...@gmail.com asked:
 We have a project which has 30+ perl/modperl modules.
 Installing those modules by hand on each host is wasting time.
 So can we just copy the directory /usr/lib/perl5/ from the already
 installed host to any other not installed hosts?
 
 We use Linux OS, perl version is 5.8.8.

That sounds like a recipe for disaster.

Some possibilities:

1) You could use the autobundle function of CPAN.pm:

perl -MCPAN -e autobundle

This will create a listing of all currently installed modules on your system.

You can then copy that list to your target systems and do

perl -MCPAN -e 'install Bundle::Snapshot_snapshot_date_time

which will do a more or less automated install of all missing modules.

Pro: Should work fine for different architectures and OS releases/patchlevels

Con: Slow. Might install a different Perl version on your system (ouch!), 
unless you edit the packlist afterwards. That would require you knowing what 
you need module-wise, though.

2) If your project is a single executable and the target systems are all of the 
same architecture, you could use PAR to generate a standalone application.

Pro: Easy to deploy - just copy one file. Doesn't mess with the distro's Perl 
installation.

Con: Not so easy to create if you have external dependencies to certain libs 
etc. PAR archive is architecture/OS release specific.

3) If you have multiple executables, then Roll your own Perl might be an 
option. Create a package subdirectory under /opt and install your own Perl in 
/opt/yourpackage/bin with the the corresponding modules in 
/opt/yourpackage/lib. To distribute, simply copy /opt/yourpackage to the target 
systems.

Pro: Doesn't mess with the distro's Perl installation. Incremental update 
capability using rsync ;-)

Con: executables have to be fixed to call the proper Perl interpreter. Package 
is architecture/OS release specific.

4) If you're using Debian or a distro derived from it, you could use 
dh-make-perl to package the required modules that are not available from the 
distro itself. For deployment, you'd need a simple installer script that would 
load the required modules from a repository or the packages that you've made. 
The deluxe version would be to package your application itself; listing the 
required packages as dependencies.

Pro: Clean integration into the distro's package management. Dependencies can 
be detected and installed if necessary. Depending on how professional you want 
to get you can keep your own repository woth multiple package versions around. 
Ideally installation could be automated to a simple apt-get install xxx on 
the target system if you package your application and use repository for your 
packages.

Con: Package management takes some time to learn. Can be tricky to set up for 
multiple architectures. Requires some effort to maintain the module packages.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: delete 20 000 records in oracle from perl

2009-08-17 Thread Thomas Bätzler
luke devon luke_de...@yahoo.com asked:
 Since i have more binary data to be deleted in the requested query , i
 have to use a external script/program to satisfy the deletion. So thats
 why i wanted to know , how can we implement multi threading for the
 situation.

You said that CPU load is high when deleting the records, and yet you want to 
do multiple delete queries at once? That doesn't sound like a good idea to me 
;-)

Also, if a delete query on a single records takes two minutes, then it might be 
worth your while to investigate the causes. Is there an index on the key you're 
using to select rows to delete? Have you had a pro look at the database 
configuration? I seem to recall that unlike consumer DBMS like MySQL, Oracle 
requires frequent tuning to optimize performance.

HTH,
Thomas


AW: Having problems getting data back to STDOUT once I assign it to a file

2009-07-21 Thread Thomas Bätzler
Wagner, David --- Senior Programmer Analyst --- CFS david.wag...@fedex.com 
asked:
   I have looked at perldoc -f open and tried a number of things. The
 line should be last line is appearing in my audittrail file, but I
 never see the EndOfProg or Error in the auditrrail or on the screen.

Try perldoc -f select:

   select FILEHANDLE
   select  Returns the currently selected filehandle.  If FILEHANDLE is 
supplied, sets the new current default filehandle for output.
   [...]

That way you could re-select() a previously saved handle to STDOUT.

HTH,
Thomas


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: How to implement ping script to monitor server up/down state in perl ?

2009-07-21 Thread Thomas Bätzler
Amit Saxena learn.tech...@gmail.com asked:
 I want a perl ping script (console based) to monitor server up/down
 state.

Why re-invent the wheel when there's already stuff like  mon 
(http://mon.wiki.kernel.org/index.php/Main_Page) or nagios 
(http://www.nagios.org/)?

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: How to implement ping script to monitor server up/down state in perl ?

2009-07-21 Thread Thomas Bätzler
Amit Saxena learn.tech...@gmail.com wrote:
 Hi Thomas,

 Thanks for the response.
 
 The client for which I am working will not allow any external utility /
 modules to be installed on their development / production environments.
 Moreover they want the solution implemented using Perl only.

Actually, mon ist pure Perl, so it should fit the bill on that count.

Depending on the OS/distro your customer is using, they might even be able to 
install a mon package from one of their trusted sources.

Even if you're not going to use mon, it should provide you with a wealth of 
ideas on how to write monitoring code in Perl.

HTH,
Thomas




--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: bug in perl?

2009-07-17 Thread Thomas Bätzler
Octavian Rasnita orasn...@gmail.com asked:
 I have tried the following calculation with ActivePerl 5.10.0 build 1004
 under Windows XP Pro:
 
 print 0.79 - 0.798;
 
 And it gave the following result:
 -0.00801
 
 which is obviously wrong.

No, it isn't. Welcome to the wonderful world of machine numbers.

Please read perldoc -q number.

 It doesn't matter too much the reasons, but is there a better way for
 doing such math calculations in perl?

If you're dealing with money, it's a common practice to work with cents and 
integers instead of using floating point numbers.

HTH,
Thomas 

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: bug in perl?

2009-07-17 Thread Thomas Bätzler
Paul Johnson p...@pjcj.net wrote:
 On Fri, Jul 17, 2009 at 12:26:58PM +0200, Thomas Bätzler wrote:
  Octavian Rasnita orasn...@gmail.com asked:
   I have tried the following calculation with ActivePerl 5.10.0 build
   1004 under Windows XP Pro:
  
   print 0.79 - 0.798;
  
   And it gave the following result:
   -0.00801
  
   which is obviously wrong.
 
  No, it isn't.
 
 Well ... yes, it is.

Let's settle on the result isn't what you'd expect if you had no prior 
experience with machine numbers ;-)

Cheers,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




AW: Time stamp in file name.

2009-07-08 Thread Thomas Bätzler
Meghanand Acharekar vasco.deb...@gmail.com asked:


 I am writing a perl script which creates a file (on Linux/UNIX) using
 system's date. 
 e.g. log_2009-07-07.gz
 
 Here is the code I wrote.
 
 #!/usr/bin/perl -w

use strict;

 # Prog for demostrating file name concatenations.
 $prefix=log;
 $suffix=.gz;

my $prefix = 'log';
my $suffix = '.gz';

 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);

my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);

 # Time
 $middle=sprintf %4d-%02d-%02d \n,$year+1900,$mon+1,$mday;

# note no \n here!
my $middle=sprintf %4d-%02d-%02d,$year+1900,$mon+1,$mday;

 print My Date : $middle\n;
 $file_name=join(_,$prefix.$middle.$suffix);

my $file_name=join(_, $prefix, $middle, $suffix );

 print New File name : $file_name \n;

__END__

HTH,
Thomas


AW: Edit text file using perl script

2009-07-07 Thread Thomas Bätzler
Alpesh Naik naik.alp...@gmail.com asked:
 I  am trying to edit the text file using perl script.
 i want to replace a particular text of file with new text.
 
 but the problem is that the new text appeared at end of file;
 
 How can i solve this problem,
 pls. help

We can help you much better if we can actually see what you're doing, so please 
include sample code.

A working pattern for modifying a file goes like this:

1. open old file or reading

2. open temporary file for writing

3. read a line from the old file

4. if the line matches your criteria, then modify the line

5. write the line to the temporary file

6. If you have not reached the end of the old file yet, continue at 3.

7. close the old file

8. close the temporary file

9. rename the old file to a temporary filename

10. rename the temporary file to the name of the old file

11. optionally, delete the old file

It's not an in-place edit, but it works. If you need to do in-place edits, you 
should look at seek() and understand the constraints of doing an in-place edit.

HTH,
Thomas

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/




  1   2   3   4   >