RE: Question on sorting file

2005-02-14 Thread Thomas Bätzler
Vishal Vasan <[EMAIL PROTECTED]> asked:
> I am trying to sort a file with records. I have tried to 
> slurp all the records present in the file to memory but the 
> memory has run out.

Read your input file in several large chunks, and sort
each as you go, saving the output to a temporary file.
Once you have a set of sorted temp files, do a merge 
of the various files to a new output file.

Here's some sample code to do the merging. You'll have
to provide your own code to pick out the key to sort on.
@tempfiles is a list of filenames with sorted partitions
of your data.



use IO::File;

sub dateline {
  my $obj = shift;

  if( defined( my $line = $obj->{'fh'}->getline() ) ){

$obj->{'line'} = $line;
$obj->{'val'} = generate_sorting_value( $line );

  } else {

if( $obj->{'fh'}->eof() ){
  $obj->{'fh'}->close();
} else {
  die "Error reading from '" . $obj->{'name'} . "': $!";
}

$obj = undef;
  }

  return $obj;
}

my @infh;

foreach my $file ( @tempfiles ){

  if( my $fh = new IO::File $file ){

my $obj = dateline( { 'fh' => $fh, 'name' => $filename } );

push @infh, $obj if defined $obj;

  } else {
die "Failed to open input file '$file': $!";
  }

}

die "Failed to open output file '$outfilename': $!" unless my $outfh = new
IO::File $outfile;

while( @infh >= 2 ){
  @infh = sort { $a->{'val'} <=> $b->{'val'} } @infh;

  # write the line with the lowest sorting value
  $outfh->print( $infh[0]->{'line'} );

  # discard filehandle "object" if there are no more lines pending
  shift @infh unless dateline( $infh[0] );
}

$outfh->print( $infh[0]->{'line'} );

while( !$infh[0]->{'fh'}->eof() &&  !$infh[0]->{'fh'}->error() ){
  $outfh->print( $infh[0]->{'fh'}->getline() );
}

__END__

HTH
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Modifying directory permission

2005-02-03 Thread Thomas Bätzler
Anish Kumar K. <[EMAIL PROTECTED]> asked:
> Is there any way in perl I can modify the permission of a 
> directory using perl scripts

Of course. Check out the builtins chmod and chown.

HTH,
Thomas


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: file input/output

2005-02-03 Thread Thomas Bätzler
Elliot Holden <[EMAIL PROTECTED]> asked:
> okay this may seem like a simple problem but here it goes:
[...]
> open(OUTFILE, ">>survey.txt");
[...]

Your web server may not have permission to create
the file in question. Always check return codes!

open(OUTFILE, ">>survey.txt") or die "Could not open file: $!";

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: flush function

2005-01-31 Thread Thomas Bätzler
Urs Wagner <[EMAIL PROTECTED]> asked:
> I have a problem on WinXP. In perl I want to read the tail of a file. 
> The  file is written with another windows program. If I am 
> using a sleep(5) before of the read command I get the new 
> tail content. It seems the program has longer to write it or 
> it is buffered.
> Is there a command in perl to flush a file?

Yes and no.

You can set autoflush on the filehandle in question,
but that will only work for your own write operations.
You can't force another process to flush pits pending
output by doing this, though.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Trapping Windows Web Activity

2005-01-28 Thread Thomas Bätzler
James W. Thompson, II <[EMAIL PROTECTED]> asked:
> Out of curiosity is there any method for trapping Windows 
> HTTP traffic transparently, without establishing a proxy 
> configuration, using Perl.

Probably not. Depending on what you want to do,
a cheap solution might be to set up a Linux box
as a gateway, and use iptables to force outbound
HTTP traffic through a proxy.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: perl substituion

2005-01-28 Thread Thomas Bätzler
Anish Kumar K. <[EMAIL PROTECTED]> asked:
> Say I have a string called returned from the text file.. 

I don't understand this part. I assume from context that
you want to use a template.

> I could very well use substition for the variables 
> individually. But it will be nice If I could substitute this at bulk..

If you don't want to use big guns to shoot sparrows
(i.e. use Template::Toolkit) then you could do it
easily like this:

#!/usr/bin/perl -w

use strict;

# put your key/value pairs into a hash
my %var = qw( name Thomas foo bar );

my $template;

# slurp in template
{
  local $/ = undef;
  $template = ;
}

# do bulk substitution
$template =~ s/##(.*?)##/$var{$1}/eg;

print $template;

__DATA__
Hello ##name##,

The value of foo is '##foo##'.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: hash slice/exists vs. grep benchmark weirdness...

2005-01-25 Thread Thomas Bätzler
 
[EMAIL PROTECTED] suggested:
> Just as an FYI, you don't need "exists" in your code at all. 
> It is just a waste of time in your example. Should be beter writen as:
> 
> print "hi" if $n{11};

Bad idea, if you consider this:

$n{'oops'} = 0;
print "hi" if $n{'oops'};
print "ho" if exists $n{'oops'};

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: "or die" question

2005-01-25 Thread Thomas Bätzler
Hi, 

> After a failed open, I want to run two statements for an "or die".
> 
> Code Quesiton:
> 
> open (TEST, ">/tmp/test")
>   or {
>   die "Could not open test file\n";
>   syslog("LOG_ALERT","Could not open test file");
>};
> 
> This does not work, but what is the "right" way to do this?  
> I know I could write a MyDie sub and pass a string to it.

For clarity's sake you could write:

if( open(TEST, ">/tmp/test") ){
  # code goes here
} else {
  # do important stuff, then die. Won't work the other way
  # 'round, just like in Real Life.
  syslog("LOG_ALERT","Could not open test file");
  die "Could not open test file\n";
}

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: RegExp equivalencies

2005-01-25 Thread Thomas Bätzler
Michael Kraus <[EMAIL PROTECTED]> asked:
> Is:
> 
> my ($id) = $item =~ /_(\d+)$/;
> 
> Equivalent to:
> 
> $item =~ /_(\d+)$/;
> $id = $1;

Yes. It's especially useful when you've got more than one 
capture in your RE.

> Wild Technology Pty Ltd , ABN 98 091 470 692 Sales - Ground 
[...]

And that'll really make you popular around here ;-)

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: parsing gzipped log files

2005-01-19 Thread Thomas Bätzler
Mariano Cunietti <[EMAIL PROTECTED]> asked:
> can anyone address me to a Perl module/function to parse 
> gzipped log files without uncompressing them via gzip/gunzip?

You have to uncompress them somehow, but you don't have to
uncompress them to a file. I regularly use code like this:

  if( $file =~ m/\.gz$/ ){
$file = "gzip -d < $file |";
  } elsif( $file =~ m/\.bz2$/ ){
$file = "bzip2 -d < $file |";
  }

  if( my $fh = new IO::File $file ){

# do something

  } else {
die "Failed to open input file '$file': $!";
  }

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Transforming a space-separated string to an array for words.

2005-01-13 Thread Thomas Bätzler
Robin <[EMAIL PROTECTED]> suggested:
> This will split up the string based on the pattern (in this 
> case, a single space. You may want to change that to gain 
> robustness, e.g. /[ \t]+/ will split on any number of spaces and tabs)

I suggest /\s+/ instead. This splits on any whitespace,
and it'll also remove trailing whitespace like those
pesky trailing \n:


#!/usr/bin/perl -w

use strict;

my $string = "foo baz bar\n";

foreach my $word (split/[ \t]+/, $string) {
  print "'$word'\n";
}

foreach my $word ( split/\s+/, $string ) {
  print "'$word'\n";
}


HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Execute a perl array

2005-01-12 Thread Thomas Bätzler
Groleo Marius <[EMAIL PROTECTED]> asked:
> i have a simple question : how can i execute an array, 
> knowing that it contains perl code?

Assuming you meant a Perl script, not bytecode:

eval join("\n",@code);

Read all about it with "perldoc -f eval".

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: wrong execution of "or"

2005-01-11 Thread Thomas Bätzler
Mauro <[EMAIL PROTECTED]> asked:
> I have a problem with my perl program because I'm not be able 
> to understand why it seems to execute both part of "or" statement.

I'm assuming you're referring to 

> system('/usr/bin/scp -qvp [EMAIL PROTECTED]:/home/clariion/cx700_perf.txt
/home/mgatt/rrd/tmp') or die "Non riesco a fare scp\n";

>From the perlfunc manpage: "The return value [of system()]is the exit
status of the program as returned by the wait call."

In this particular case, the return value will be 0 on success. This
is unlike most Perl functions where a boolean false result will indicate
a problem. To make your code work, check for the expected result code:

system(...) == 0 or die;

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Javascript issue

2005-01-11 Thread Thomas Bätzler
Anish Kumar K. <[EMAIL PROTECTED]>
> Sorry to put in this PL forum

Just don't do it.

> Say I have  Javascript alert like this.
> 
> 
> when I preview this I get the alert window it is working 
> fine. But The caption of the window is" Microsoft Internet Explorer".
> 
> Is there any way to change it...I mean some user defined strings.

No. And for obvious reasons, this is a Good Thing.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: linked list

2005-01-11 Thread Thomas Bätzler
Christian Stalp <[EMAIL PROTECTED]> asked:
> Does anybody has any experience with making liked lists in perl.

Perl's arrays are really linked lists - check out the
built-in function splice().

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: CPAN

2005-01-11 Thread Thomas Bätzler
Daniel <[EMAIL PROTECTED]>
> I made a mistake when setting up CPAN, I chose Central 
> America as my Continent, then the only option was to chose 
> Costa Rica as my Country.
>  Not that I have anything against Costa Rica, very lovely 
> place will visit soon, but would like a ftp server closer to 
> my real home.  I looked thru the h option and the perldocs, 
> but cannot figure out how to reload my info.  Please help!!

In interactive mode ("perl -MCPAN -eshell") run "o conf init".

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: GD isn't outputting image data

2005-01-11 Thread Thomas Bätzler
Owen <[EMAIL PROTECTED]> suggested:
> Well perhaps for a single debugging line, it doesn't matter 
> too much, but consider a program where endless things can and 
> do go wrong. Peppering your script with
> 
> or die "Can't open the file Data1 $!\n"; or die "Can't open 
> the file Data2 $!\n"; or die "Can't open the file Data3 $!\n"; etc
> 
> really helps track down where to look
> 
> The rule is to always check the return value

I'd go even a step farther and suggest that you make sure of
your arguments, too:

open( IN, $file ) or die "Can't open '$file': $!\n";

That helps a lot in tracking down problems that arise
because of wrong assumptions (i.e. that you've got a
filename right).

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Execute interactive shell scripts from perl?

2005-01-11 Thread Thomas Bätzler
Myers, Drew <[EMAIL PROTECTED]> asked:
> I've been lurking on this list for a while, but this is my 
> first email.  
> 
> I've written a series of ksh scripts, that prompts the user 
> for information, and reads the user's input.  
> 
> I'd like to call these ksh scripts from within my perl script.  

You might want to look into the open2 and open3
functions, depending on your needs. Their use and
potential pitfalls are discussed in the perlipc
manpage ("perldoc perlipc")

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: :UserAgent

2005-01-04 Thread Thomas Bätzler
Ing. Branislav Gerzo <[EMAIL PROTECTED]> asked:
> just pretty simple question: is LWP::UserAgent encode URL ?
> for example I have:
> 
> my $ua = LWP::UserAgent->new;
> my $resp = $ua->get('http://something.net/this:is+just test');
> 
> my question is, if LWP first encode (escape) path in URL as 
> is written in RFC 1738, or I have to care about it in my script ?

LWP does it for you. That can be a major PITA when you're trying
to call braindead CGI code that can't handle quoted-printable
characters in an URI.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: How to monitor a scritp

2004-11-23 Thread Thomas Bätzler
Ing. Branislav Gerzo <[EMAIL PROTECTED]> wrote:

> Mauro [M], on Tuesday, November 23, 2004 at 10:44 (+0100) wrote:
> 
> M> I made a script that works fine.
> M> When a try to run it in crontab it seems it doesn't work.
> 
> it is maybe path related problem. Try tu run exactly that 
> script as in crontab, but be in other directory, where 
> script, or crontab runs.

If you are calling external commands by just their name,
then make sure their location is in $PATH. Better yet,
use absolute path names to run them (and to check that
they are present, giving an error when they are not).

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: How do I set POST vars from a perl script

2004-11-05 Thread Thomas Bätzler
A Taylor <[EMAIL PROTECTED]> asked:
> I am trying to set some HTTP header variables in a perl 
> script that I can then pick up in another script.
> I want to create a situation as if some one had POSTed 
> variables from a form. I then want to pick these variables up 
> in an .asp script.

You can use LWP to make a POST request to another CGI script:

#!/usr/bin/perl -w

use strict;
use LWP::UserAgent;


sub post_url {
  my( $url, $formref )  = @_;

  # set up a UserAgent object to handle our request
  my $ua = new LWP::UserAgent(timeout => 300);

  $ua->agent('perlproc/1.0');

  my $response = $ua->post($url, $formref );
  
  if( $response->is_success ){
return $response->content;
  } else {
die $response->status_line;
  }
}


my $url = "http://baetzler.de/cgi-bin/listcgiparam.cgi";;

my %param = ( 'foo' => 'bar', 'email' => '[EMAIL PROTECTED]' );

print post_url( $url, \%param );

__END__

HTH,
THomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Mod_Perl Target Headers

2004-11-05 Thread Thomas Bätzler
James Taylor <[EMAIL PROTECTED]> asked:
> Should be a pretty simple question, looking for an option in 
> header_out to target a frame.
[...]
> Was hoping I could do something like:
> $r->header_out('Target'=>'_top');
> 
> but that doesn't seem to work.  Any suggestions?

The destination window for a HTML request is always chosen
by the browser - after all "target" is link attribute and
not a HTML header. 

The only thing you could possibly do is output a page that
contains some JavaScript to load a new _top page.

HTH,
Tho,as

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Newbie: Perl Vs Shell

2004-10-29 Thread Thomas Bätzler
"Chris Devers" <[EMAIL PROTECTED]> wrote:
On Fri, 29 Oct 2004, Thomas Bätzler wrote:
Chris Devers <[EMAIL PROTECTED]> claimed:
[...]
> well written shell scripts don't need Perl and well written Perl
> scripts don't need external shell commands.
I think that's the "ivory tower" point of view. Down here in the
trenches, it's more like "a well-written Perl script uses shell
commands where it makes sense". Obviously the art is in knowing where
it makes sense and where not.
[...]
Likewise, shell scripts with lines like this:
grep 'foo' logfile \
 | perl -pe '$l=$_; ($s=$l) =~ m/^([0-9])+/; print scalar localtime $s, " ";' \
 | sed -e 's#\( 200[0-9]\) 1[0-9]*#\1#' -e 's#\(.*\)#   \1#' \
 >> $htmllog
Are complex enough that it's probably worth considering rewriting the
whole thing in Perl. Perl is a much bigger program than most of the
standard shell tools, so a script like this is probably slower than it
needs to be.
One might argue that using sed as a filter for a Perl program is dubious -
after all, you already have the line you're interested in, so why not
do it all in Perl. On the other hand, it's probably a command line that
was plugged together on the fly, to do just one job.
In one point you're wrong, though - for selecting lines from a file and
mangling them into another format, a hybrid of shell grep and perl is
actually much faster than a pure Perl implementation - from personal
experience I'd say 1.5 to 2 times on a single CPU system. If you're on
a SMP box, probably even faster. This is no doubt because grep uses
a simpler pattern matching algorithm, and also because it's much more
efficient on I/O.
Moreover, to get this down to a reasonable line length, it
uses an obtuse style that would really be more readable as a Perl script
opaque? In any case, it looks like the person who wrote the code was
not very proficient in Perl. Otherwise (s)he's used something like
   perl -pe 's/^(\d+)/localtime $1/e'
to turn time_t timestamps to human-readable dates ;-)
spread out over several more lines. In the long run, the pure Perl
version would be easier to maintain, even if in the short term it seems
more expedient to kludge in a tricky bit in the shell script using a
single call to Perl, then reverting to shell tools afterwards.
Well, I wouldn't argue with the value of setting up proper scripts
that ones colleagues can use, too. Throw in a bit of Getopt::* and
things get downright luxurious ;-)  Still, it's not Perl for Perl's sake,
so if I can be more efficient by tying in other tools, I do that. And
obviously Perl was meant for stuff like that.
What's expedient isn't always a good idea in the long term.
Who could argue with that ;-)
Thomas 

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>



RE: Newbie: Perl Vs Shell

2004-10-29 Thread Thomas Bätzler
Chris Devers <[EMAIL PROTECTED]> claimed:
[...]
> well 
> written shell scripts don't need Perl and well written Perl 
> scripts don't need external shell commands. 

I think that's the "ivory tower" point of view. Down
here in the trenches, it's more like "a well-written
Perl script uses shell commands where it makes sense".
Obviously the art is in knowing where it makes sense
and where not.

Cheers,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: ftp w/o using Net::FTP

2004-10-28 Thread Thomas Bätzler
James P Donnelly <[EMAIL PROTECTED]> asked:
> I am only trying to login into a server, travese to the 
> correct directory, dump a file and quit.  I have hacked 
> together something that gets me to the server and
> then it seems to hang at the login..   Has anyone written 
> something like 
> this w/o use of the module?  Any insight would be very helpful
> 
> Thanks -- Jim
> 
> 
> $cmd = 'rftp';
> $rftp_commands =
> "open
>  $fHost
>  $user
>  $pass
>  quit
> ";
> 
>   open(CMD,"|$cmd");
>   print CMD $rftp_commands;
>   close(CMD);

The way it looks you're trying to ram a whole set of commands
down the FTP server's throat at once. No wonder it's choking.

What you should do is use IPC::Open2 so that you're able to
read the output from the FTP program. Then you can script your
way through the process, sending commands only when the client
is prompting for them.

See the perlipc manpage for more info on IPC::Open2.


HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: using 'my' problem

2004-10-27 Thread Thomas Bätzler
Murphy, Ged (Bolton) asked:
> In order to use the array @files in the below code outside of 
> the subroutine, so I need to declare @files globally?
> I'm getting errors at the moment: Global symbol "@files" 
> requires explicit package name
> 
> If so, where is the correct place to declare them in terms of 
> neatness? At the start of the program? above the subroutine?

That depends on your programming style. Right above the loop
would do.

Personally, I like to declare my globals in a special section
at the top of my program - sometimes even with a short comment
as to what they're supposed to hold. I find this helps me when
I look at the code much later.

YMMV.

> The information contained in this message or any of its 
> attachments is confidential and is intended for the exclusive 
[...]

Blah. Could you please get rid of that when posting to the list?

Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: speed up string matching

2004-09-23 Thread Thomas Bätzler
Hi, 

c r <[EMAIL PROTECTED]> asked:
> I need to match an expression and its reverse to a very long string.
> When a match occurs all matching should stop and the position 
> of the match should be returned.

Could you please illustrate this with an example or two?

Unless you specify the /g modifier, the RE engine stops at
the first match. Use the pos function to find the position
of the match.

> Question1: can I match the forward and reverse expression to 
> the string on the same time and thereby save half the time it 
> normally would take to find a match or does the matching just 
> get slower?

Well, you'd have to merge your expressions somehow - the easiest
way would be to try and match /expr-a|expr-b/ but then I suspect
that for all but simple cases two separate matches would be faster.

> Question2: is the "fork" function what I should use in order 
> to match a string with multiple expressions simultaneously?

Well, there is a certain overhead involved in keeping your processes
synchronized that would only be outweighed if you had a multi CPU
machine where both processes could run at once in the first place.
Even then it's a hassle.

If I were you I'd focus my energy in optimizing the expression.
If you're going to match many long strings with the same RE, you
could use the /o modifier to benefit. Also, you could try wether
a study() of the input strings speeds things up.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: how to change values of @INC

2004-09-22 Thread Thomas Bätzler

Bernd Mueller <[EMAIL PROTECTED]> asked:
> Would someone be so nice to explain me how i change the 
> values in @INC, because i know where to find this SiteDefs.pm.

You could use the "use lib" pragma, like

use lib qw(/path/to/my/modules);

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Using reference or throw valuables to sub ?

2004-09-08 Thread Thomas Bätzler
Bee <[EMAIL PROTECTED]> asked:
> Is that if I  throw the array to another sub also means the 
> array would be copied and then pass to the target sub ?
> while reference is using the same data in system memory?

Yes. Use references, unless you need to munge the array in the
sub you're calling.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Splicing Hash problem

2004-09-06 Thread Thomas Bätzler
Edward WIJAYA <[EMAIL PROTECTED]> asked:
> How can I take out/splice(?) the element of that hash that 
> start with '1' and store it into another hash. So in the end 
> I will have two hashes:

Off the top of my head, I'd say

my @temp = grep /^1/, keys %myhash;
my %myNEWhash;
foreach my $k (@temp){
  $myNEWhash{$k} = myhash{$k};
  delete myhash{$k};
}

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: awk like question

2004-08-13 Thread Thomas Bätzler
<[EMAIL PROTECTED]> asked:
> How can I print certain fields delimited by ' '?
> In awk I would write awk '{print $1, $6}' filename

In Perl, that would be

perl -lane 'print "$F[0] $F[1] $F[5]"' filename

See the perlrun manpage about all of the command line
switches. Here I use

-e - run Perl code specified in the following argument
-n - assume a basic loop like while(<>){ ... } around
 the Perl code.
-l - Add a cr/lf (or whatever is suitable) to each print
-a - run in autosplit mode, i.e. split each input line
 to the @F array.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: how to embed c code in perl programs

2004-08-13 Thread Thomas Bätzler
Karthick <[EMAIL PROTECTED]> asked:
> Is it possible to embed C/C++ codes into perl programs. 
> (Actually I want to make use of an API, that could be used 
> with with C).

It's not exactly simple, but with h2xs you can create a Perl
module out of standard C libraries. Well, h2xs creates the
module framework and also takes a stab at creating the proper
glue code to access your API, but probably you'd have to tweak
it a bit to get it to work.

The other alternative would be Inline::C which allows you to
embed C code in your program.

Both alternatives require the proper build environment for your
Perl version.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: E-mail Parsing

2004-08-04 Thread Thomas Bätzler
[EMAIL PROTECTED] <[EMAIL PROTECTED]> asked:
> I'm have a email in a text file. From this file I would like 
> to get the sender information, the attached files and the 
> body of the e-mail.
> 
> Is there something simple to do this?

Yeah. MIME::Parser from the MIME-tools distribution.

HTH,
Thomas


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: swapping in perl

2004-07-23 Thread Thomas Bätzler
Hi,

Jaffer Shaik <[EMAIL PROTECTED]> asked:
> I want to swap 2 variables without using a tempoarary variable.

( $a, $b ) = ( $b, $a );

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: __DATA__ Token Question

2004-07-22 Thread Thomas Bätzler
Bastian Angerstein <[EMAIL PROTECTED]> asked:
> Could I change the contens of the datatoken (filehandle)
> during the runtime of the skript?

That depends on the OS and implementation - for some
you can do that, for others you can't. And the big
question is of course if you should do that.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: new window on redirect

2004-07-13 Thread Thomas Bätzler
Tim McGeary <[EMAIL PROTECTED]> asked:
> > Sort of. What I don't understand is why do you have to decide on the
> > server side, post-request that the result will be in a new window? 
> > Couldn't the original "portal" page just use targets like normal?
 
> It's a database driven site and so, unfortunately, it is all server
> side, at least for this purpose.  So are you telling me 
> there's no real way in perl to do this?

Actually, there is no real way to do that in any
programming language. It's not a Perl-specific issue.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: removing duplicate array values

2004-04-21 Thread Thomas Bätzler
Peterson, Darren - Contractor.Westar asked:
> I'd like to remove duplicate values from an array
[...]

This is a FAQ. Run "perldoc -q duplicate" for the answer.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Test For Dupplicate elements in an array

2004-04-20 Thread Thomas Bätzler
<[EMAIL PROTECTED]> asked:
> I need to test if an array holds duplicates, and if so do something. 

Try

use strict;
use warnings;

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

foreach my $item (@array){
  warn "duplicate item $item" if exists $have{$item};
  $have{$item}++;
}

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Sendmail::Milter

2004-04-19 Thread Thomas Bätzler
Dirk Tamme <[EMAIL PROTECTED]> asked:
> I get the error message:
> /usr/bin/perl: relocation error: 
>
/usr/lib/perl5/site_perl/5.8.0/i586-linux-thread-multi/auto/Sendmail/Milter/
Milter.so: 
> undefined symbol: smfi_setconn
> 
> It seems that there is missing something.

OTTOH, I'd say your sendmail isn't built with Milter support or
the Milter libs aren't installed.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: AW: book suggestion for atypical beginner

2004-04-08 Thread Thomas Bätzler
Randall wrote:
> In fact, let me take this one step further.  I've been told recently
> (although I might be misremembering) that O'Reilly will publish NO
> MORE CDs because of rampant piracy.

And the fact that they want to sell Safari subscriptions
has nothing to do with it, right? ;-)

Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: can somebody tell me what this means

2004-03-11 Thread Thomas Bätzler
Hi,

sam lehman <[EMAIL PROTECTED]> asked:
> i got his code from a program i found, and i was wondering 
> that the ? and 
> the : are for?
> 
> $target = (@digits % 2) ? ($digits[int(@digits/2)]) : 
> ([EMAIL PROTECTED]/2-1]);

This is the so-called ternary operator. It's roughly
equal to saying

if( (@digits % 2) > 0 ){
  $target = $digits[int(@digits/2)];
} else {
  $target = [EMAIL PROTECTED]/2-1];
}

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Perl 6

2004-02-02 Thread Thomas Bätzler
Dan Brow <[EMAIL PROTECTED]>
> Any one know when perl 6 will be released for production use?

I doubt anybody on this list will be able to give you
anything else but "when it's done" as the answer.

Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: New to PERL and Need Help

2004-01-13 Thread Thomas Bätzler
KENNETH JANUSZ <[EMAIL PROTECTED]> asked:

> Sent: Tuesday, January 13, 2004 2:57 PM
> I am new to the world of PERL and need help to get started.
[...]
> Any help with books for beginners or web sites will be 
> greatly appreciated.  Keep it very simple.

Go grab ActiveState's Perl port for windows at
http://www.activestate.com/Products/Download/Download.plex?id=ActivePerl
if you haven't done so already. You'll want the MSI package.

Once you've got it on your HD, open the installation
directory in the Explorer, find the HTML folder and
double click on index.html. Bookmark this page; it's 
your complete Perl documentation.

Search in the right pane for perlfaq2 and click it.
There's a list of recommended books on that page.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Problem with 'cc' command in CPAN makes (i.e., Bundle::CPAN)

2003-12-11 Thread Thomas Bätzler
Hi,

glidden, matthew <[EMAIL PROTECTED]> asked:
> I'm using the CPAN module to build my modules and have hung 
> up just trying install Bundle::CPAN. Installing Data::Dumper,
> for example, shows a 'cc: command not found' error during make.
> My system uses gcc instead of cc, but I'm not sure where to 
> set this option.

That information lives in Config.pm, which is created
during the build process of Perl. Tweaking this might
or might not help you - on Win32 at least, you can't
build Perl modules for ActiveState's binary port with
GCC. Your best bet is to roll your own Perl, of course.
Apart from that, you might want to try and install the
same compiler environment as used by the peope who built
your Perl.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: -e with single quotes

2003-12-11 Thread Thomas Bätzler
Dan Muey <[EMAIL PROTECTED]> asked:

> I'm tryign to do a perl -e '' command and am wondering if it is 
> possible to do single quotes inside the single quotes.

perl -e "print \"joe's mama\n\";"

perl -e 'print "joe".chr(39)."s mama";'

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Get file size without downloading

2003-12-10 Thread Thomas Bätzler
Hello,

usef <[EMAIL PROTECTED]> asked:
> Is there any way to get the size of a file without downloading it?
> I want to write a program using LWP to download a file only 
> if it is bigger than 3K but smaller than 500K.
> So I need to know the file size in the first place.

Try making a HEAD request - that should return
file size and last modification date. This
obviously will not work for CGI URLs.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




RE: Perl and MS Access

2003-12-04 Thread Thomas Bätzler
Hello Shaunn,

> I think I've seen it, but I don't know where -
> 
> Isn't there a method to use Perl to connect to
> some MS Access database and extract the
> data into some other format (say, text).

That works fine with the DBD::ODBC module. If you
have got large records in the database, you should
set $dbh->{LongReadLen} to the maximum record size,
otherwise the records will be truncated.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: invoking external programs

2003-11-13 Thread Thomas Bätzler
Hi,

[EMAIL PROTECTED] <[EMAIL PROTECTED]> asked:
> I'm actually building a web interface to a news group server (INN).
> One of the feature is to allow a few users to create and 
> delete newsgroups from the web.

Hopefully only for your local news hierarchy ;-)

> Normally, from the shell, I would perform the following operations to 
> create or remove a newsgroup (I will setuid the ctlinnd  because ctlinnd 
> needs to be executed as the "news" user):

That is not the best possible solution. The best would doubtless
be to set up a small tcp service that will run these commands on
your behalf as the news user. The next best alternative would be
to use sudo to allow your web server user to run the required
commands as the proper user.

> /usr/local/news/bin/ctlinnd pause "modification of active file"
> /usr/local/news/bin/ctlinnd rmgroup/newgroup name_of_the_newsgroup
> /usr/local/news/bin/ctlinnd reload active "reload active file"
> /usr/local/news/bin/ctlinnd go "modification of active file"

How long will those commands take to execute? Bear in mind that
users as a species are dumb and that sh*t will happen, so you
might want to consider that a user could hit the stop button
while these jobs are still running. The web server will kill
your CGI program and that will certainly also kill a spawned
ctlinnd.

> If the server successfully performed the command, ctlinnd 
> will exit with a status of zero and print the reply on 
> standard input.
[...]
> It's not clear to me how I could retrieve the status code.

> I would also like to know whether the way I use system() is
> right or if there is a better way to do what I'm tryining to do.

I would say that system seems to be suited best to the task
at hand. Not only does it allow you to read the status code
on completion, but you can also check for crashes of the
called program.

from "perldoc -f system":

You can check all the failure possibilities by inspecting $? like this:

$exit_value  = $? >> 8;
$signal_num  = $? & 127;
$dumped_core = $? & 128;

[...]
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> 
> use CGI;
# one I find quite useful for CGI development
use CGI::Carp qw(fatalsToBrowser);

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: When is Perl 6 coming out?

2003-11-13 Thread Thomas Bätzler
km <[EMAIL PROTECTED]> asked:
> i am  just curious -- is perl 6 coming with a compiler ?

That depends on your definition of compiler.

It certainly has a compiler that creates byte code, just
as all of the current Perl versions. I don't know wether
it will have a compiler like PerlEx bundled.

What I know is that Perl 6 will have a cleaner separation
of compiler and virtual machine. In fact, Perl 6 and its
virtual machine Parrot are developed by different teams.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: Starting Perl

2003-11-11 Thread Thomas Bätzler

yomna el-tawil [mailto:[EMAIL PROTECTED] asked:
> i'd like to say first that i'm using activePerl ,
> under windows.

If you've installed that properly, you're set.

> for O'Reilly, i couldn't subscribe or even have the 14
> days trial because i don't have a credit card.. :(
> I have a question, because really i couldn't help
> myself...
> I don't know where to write the Perl code...

Basically, it doesn't matter. Preferably, create
a directory for your Perl code somewhere on your
disk drive. Use any editor you like (my preference
is TextPad from http://www.textpad.com/) and write
your code, i.e. for starters:

use warnings;

print "Hello, World!\n";

Save that as hello.pl in your directory. Now, open a
DOS box (i.e. Start Menu => Run => cmd.exe on Win2k/XP),
and change to your Perl directory. Now you can run your
code using the command

perl hello.pl

If you use Textpad, you can also integrate Perl in the
editor as a tool. Write your code, save it, and the hit
a simple key combo like CRTL+1 to imediately run your
code. The output is catured in another editor window.

HTH,
Thomas

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: how do I pass null arguement?

2003-10-10 Thread Thomas Bätzler
Hi,

[EMAIL PROTECTED] wrote:
> How do I pass a null variable as an argument? Sometime I may want a
> wrapper sub as below:
> 
> Example,
> ...
> sub procName
> { my $fname = $_[0];
>   my $lname = $_[1]];
> }

Alternatively, you could write either

  my $fname = shift;
  my $lname = shift;

or even

  my( $fname, $lname ) = @_;

> 
> my procByLastName{ mySubA(null, "doe"); }
> ...
> 
> This is the error message:
> Bareword "null" not allowed while "strict subs" in use

Perl's notion of NULL would be undef, i.e. not defined.
As such, it's distinct from an empty string or zero as
a numeric value.

The function defined() helps you to test wether a value
is undef or not.

BTW, since you ask about argument passing and undef,
a nice way to handle setting defaults for arguments
is using this syntax:

my $var = shift || "default";

Works great if your expected arguments are always
defined and true. It would set $var to "default"
if you pass in an empty string or the number 0,
though.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: regex, is this possible?

2003-10-08 Thread Thomas Bätzler
Jerry Preston <[EMAIL PROTECTED]> asked:
> I am trying to break down the following:
> 
>printf("numsteps=%d  i=%d im=%g vfr=%g 
> \n",numsteps,i,imeas,vforce);
> into
>"numsteps= numsteps  i=i im=imeas vfr=vforce \n"
> 
>printf ("\noriginal cap = %g, offset = %g", *ci, cap_offset);
> into
>"\noriginal cap = ci, offset = cap_offset";
> 
> I am wanting to improve my limited regex skills.  Is the 
> above possible or
> is there a better way with one method?

Off the top of my head:

s/printf\s*\(\*(".*?").*?\);/$1;/g

Anchoring the end of the pattern with ");" should
insure you against mismatches when there is a
function call instead of a variable in the argument
list. Still, the pattern fails for weird templates
like

printf("some \"quoted\" text" ();", foo, baz, bar );

If you want to have a bullet-prrof solution, you
should check out Text::Balanced, which takes care of
stuff like balanced quotes, brackets and such.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: another how to regex ?

2003-10-07 Thread Thomas Bätzler
Hi,

Jerry Preston <[EMAIL PROTECTED]> asked:
> I am trying to change some text from:
> 
>  if ( (fabs(log(im[ii]/im[ii-1])/vstep) >
> fabs(3*log(im[ii-1]/im[ii-5])/(4*vstep)) )  && ((im[ii] > ifr[x]) ||
> (im[ii-1] > ifr[x]))  ) {
> to
>  if ( (fabs(log(im[ii]/im[ii-1])/vstep) > fabs(3 *
> log(im[ii-1]/im[ii-5])/(4 * vstep)) )  && ((im[ii] > ifr[x]) 
> || (im[ii-1] >
> ifr[x]))  ) {
>^^^
> ^^^ 
> with the following:
> 
>   s/(?=[A-z|0-9]+)\*(?=[A-z]+)/' * '/g;
> 
> What am I doing wrong?

Hm, wouldn't this do the job?

s/\s*(\*{1,2})\s*/ $1 /g;

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: Add text to beginning every line

2003-10-07 Thread Thomas Bätzler
Hi,

Chris Charley <[EMAIL PROTECTED]> wrote:
> Should be (works correctly):
> 
>  while (<>) {
>s/^/Line: $. /;
>print;
>  }
> 
> Then the command could be:perl prepend.pl somefile.txt > 
> somefile.new
> which would correctly print to the 'new' file the 
> somefile.txt file with the line numbers prepended.

I would even suggest 

perl -i.bak -pe 's/^/Line $.: /' 

This will do the replacement on one or more files 
whose names oyu give on the command line. Perl
will then create backup files with the .bak extension
and modify the original files.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: easiest `cat` in perl

2003-10-02 Thread Thomas Bätzler
Joshua Colson [mailto:[EMAIL PROTECTED] suggested:
> sub load_file {
>   my($file,$html) = shift;
>   $html = '';
>   open(FILE, "$file") or die "Cannot open $file for reading: $!"
>   while() { $html .= $_; }
>   return $html;
> }

Instead of "while() { $html .= $_; }", you
could use "$html = join("", )".

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: easiest `cat` in perl

2003-10-02 Thread Thomas Bätzler
Todd Wade <[EMAIL PROTECTED]> wrote:

> "Gary Stainburn" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
[...]
> > One thing you forgot was to close the file.  Also, don't 
> > forget that you can do it with less typing:

Closing files is optional in Perl ;-) Filehandles
will either be closed when the program terminates
when the filehandle is opened the next time.

> > $file = "/location/of/header.incl";
> > open (FH, "$file") or die "Cannot open file $file $!";

If you wanted to pipe other stuff than just plain
text, then 

binmode(FH);

would be a good idea for portability.

> > print while();

This is bad because it first pulls in the file to
build the list.

> > close(FH);

> print ;
> 
> print takes a list of arguments:

Just to be nit-picking (and to repeat what I learned
from a M.J. Dominus talk at YAPC::EU this year ;-))

"print'ing a list is slower than printing a single
(large) scalar."

In this particular case it might be worthwhile to
use "slurping": We create a scope in which the input
record separator $/ is temporarily set to undef.
Reading from  then returns just a single record.

The payoff - printing is nearly twice as fast.

#!/usr/bin/perl -w

use strict;
use Benchmark;

my $file = "out.txt";
my $count = 2;

open( OUT, ">$file") or die "Can't open '$file':$!";

print "print using a scalar:\n";
timethis( $count, 'open(IN, "$0"); { local $/; undef $/; print OUT ; };
close( IN)' );

close( OUT );
unlink $file;

open( OUT, ">$file") or die "Can't open '$file':$!";

print "print using a list:\n";
timethis( $count, 'open(IN, "$0"); print OUT ; close( IN)' );

close( OUT );
unlink $file;
__END__
print using a scalar:
timethis 2:  6 wallclock secs ( 2.85 usr +  2.44 sys =  5.30 CPU) @
3775.72/s (n=2)
print using a list:
timethis 2: 11 wallclock secs ( 7.88 usr +  2.67 sys = 10.56 CPU) @
1894.84/s (n=2)

Cheers,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: explicit vs implicit syntax

2003-10-02 Thread Thomas Bätzler
[EMAIL PROTECTED] asked:
> Here's an excerpt about the & from orielly and what the heck 
> does it means:
> 
> "...If a subroutine is called using the & form, the argument list is
> optional. if ommitted, no @_ array is setup for the routine; 
> the @_ array at the time of the call is visible to subroutine instead."

If in doubt, run a test ;-)

#!/usr/bin/perl -w

use strict;

sub showargs {
  print "arguments are: " . join(', ', @_) . "\n";
}

sub test {
  print "Arguments for test() are: " . join(', ', @_) . "\n";
  print "Calling &showargs - ";
  &showargs;
  print "Calling &showargs() - ";
  &showargs();
  print "Calling showargs - ";
  showargs;
  print "Calling showargs() - ";
  showargs();  
}

test qw(foo baz bar);
__END__

> So, is there a better or worse? both ways works for me. I just started
> going back and putting the & onto the sub ;) I don't like it 
> the & but I thought that you need it.

See for yourself - there's only one use for the ampersand,
and it's obscure. My advice would be to avoid using it even
in the one situation where it would make sense - when passing
@_ as an argument to your function. Sure, it is idiomatic Perl
at its best, but it also makes a program harder to read and
understand.

In other words - save it for Perl Golf ;-)

HTH,
Thomas

PS: Perl Golf - writing code with as little (key-)strokes as
possible.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: index

2003-10-01 Thread Thomas Bätzler
Ronen Kfir  asked:
> The following script meant to calculate simple math drills, 
> such as 5 *
> 9 or 4 + 3, written in one line. What I cannot comprehend is the lines
> marked with ---. What do they do? Why is there a "0 < index..." 

That looks like somebody wrote a C program in Perl. (S)he
is using (r)index and substr to pluck apart the the input.

The "0 < index ..." construct is basically there to determine
wether the operator was a + or a *. Writing the constant on
the left hand in a comparison is a fairly common way to find
a missing "=" in an numerical eqality check - if you want to
check wether $a is 0, then the typo "0 = $a" will produce an
error, while the assignment "$a = 0" will most likely be
a nasty bug.

> $line = ;
> chomp $line;
> 
> $first_space = index($line , " ");
> $a = substr($line, 0, $first_space);
> 
> $last_space = rindex($line , " ");
> $b = substr($line, $last_space+1);
> 
> 
> --- if (0 < index($line, "*")) {
> print $a * $b, "\n";
> }
> --- if (0 < index($line, "+")) {
> print $a + $b, "\n";
> }

Off the top of my head I'd suggest a different approach:

#!/usr/bin/perl -w

use strict;

# I like to read my test cases from the file itself
while( defined( my $line =  ) ){
# while has put the line in $_ for us
# this is also the variable that many
  # functions act on by default

# remove all whitespace from the line   
$line =~ s/\s//g;

# see if the line we read matches our
# pattern. If it does, we print the
# formula and the result.

# The Pattern assigns the following
# variables if it matches:
# $1 = the whole shebanf
# $2 = left operand ( optional minus, at least one digit
# $3 = operator (one of +, -, *, / )
# $4 = right operand
if( $line =~ /((-?\d+)([-+*\/])(-?\d+))/ ){
print "$2 $3 $4 = " . eval( $1 ) . "\n";
}
}
__DATA__
1+1
 3 + 7
2 * 3
6 - 8

If you like oneliners, you could always write that as

perl -ne 's/\s//g;/((-?\d+)([-+*\/])(-?\d+))/&&print "$2 $3 $4 =
".eval($1)."\n"'


HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: To quotes or not quotes parameter

2003-09-29 Thread Thomas Bätzler
[EMAIL PROTECTED] <[EMAIL PROTECTED]> asked:
> what is the proper way to pass a parameter for something like
> $cgi-param(username)?
> 
> as far as i know it, this works for me:
> 
> $cgi-param(username);

Don't do that. Using barewords as strings can
break your code if you later on introduce a
sub with the same name in your code. Besides,
this obviously doesn't work for Perl reserved
words anyways.

Instead, use either:

> $cgi->param("username");
> $cgi->param('username');

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: Order of Command Line Options

2003-09-26 Thread Thomas Bätzler
Hi,

Jeff Westman [mailto:[EMAIL PROTECTED] asked:
> Why does the order of these options matter?
[...]
> $ nslookup someServer | perl -en 'print qq($_);'
> 
> $ nslookup someServer | perl -ne 'print qq($_);'

-e must be followed by the code:

$ perl --help

Usage: perl [switches] [--] [programfile] [arguments]
[...]
  -e 'command'one line of program (several -e's allowed, omit
programfile)
[...]

So what does your first example do? Try this:

$ perl -w -en 'print "Hello, World!\n"'
Unquoted string "n" may clash with future reserved word at -e line 1.
Useless use of a constant in void context at -e line 1.

HTH,
Thomas
"-w is your friend"


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: Getting started in Perl for Windows

2003-09-25 Thread Thomas Bätzler
Dillon, John [mailto:[EMAIL PROTECTED] asked:
> Is there a gobble-di-gook looker-upper for perl.  For 
> instance, if I don't
> know what '@_' is saying, as in:
> 
> my($email, $orig_email) = @_;

Look at the perlvar manpage. @_ is the array that has the
parameters passed to a function.

The above line would assign the first two arguments passed
to the function to the two named variables.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: Getting started in Perl for Windows

2003-09-25 Thread Thomas Bätzler
Dillon, John [mailto:[EMAIL PROTECTED] asked:
> When I am in a black command.com screen with CPAN> prompt, 
> where am I?  Why can't I cd to c:\?

That would be the CPAN prompt. Try "help" for a terse
command listing, "quit" to exit back to the DOS prompt.

CPAN is the Perl module installer. Check out the CPAN
manpage for details.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: One Time Only Code in Sub

2003-09-24 Thread Thomas Bätzler
Hi,
James Edward Gray II [mailto:[EMAIL PROTECTED] asked:
> I would like to add some code to a sub that only needs to be run the 
> first time the sub executes, or before is fine.  If I add an INIT { } 
> block at the beginning of the sub, would that do it?  Are there other 
> ways?  Thanks.

If you don't mind using code references, you could try this:

#!/usr/bin/perl -w

use strict;

my $fun;

$fun = sub {
  print "Just initializing...\n";
  
  $fun = sub {
print "Now it's the real deal\n";
  };
};

foreach (qw( 1st 2nd 3rd )){
  print "$_ call: ";
  $fun->();
}
__END__

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: regex. help

2003-09-24 Thread Thomas Bätzler
Hi,

Pandey Rajeev-A19514 [mailto:[EMAIL PROTECTED] asked:
> I have a question regarding matching strings that have 
> embeded perl special characters.
> 
> $abc = 'MC10.G(12)3c';
> $efg = 'MC10.G(12)3c';
> 
> Now I want to check whether they are same or not by doing
> if ($abc =~ /$efg/) { do something;}

Why not use $abc eq $efg if you only want to check for
equality?

> For this I need to insert a '\' before every special char. 
> Can some one tell me an easy way to do ?

You can also use the qr operator to quote metacharacters
in a string or scalar value:

my $re = qr( $efg );

if( $abc =~ /$re/ ) {...}

See the section "Regexp Quote-Like Operators" in the perlre
manpage for details on qr().

HTH,
Thomas


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



RE: list-parsing problem

2003-09-19 Thread Thomas Bätzler
Marcus Claesson [mailto:[EMAIL PROTECTED] asked:
> I have a silly little list-parsing problem that I can't get my head
> around, and I'm sure some of you have come across it before.

Sure. Looks like homework ;-)

HTH,
Thomas

#!/usr/bin/perl -w

use strict;

my %unique;

while(  ){
  my( $key, $value ) = split;
  
  $unique{$key}->{$value}++
}

foreach my $key ( sort keys %unique ){
  print "$key: " . join( ", ", sort keys %{$unique{$key}} ) . "\n";
}

__DATA__
1   a
2   b
2   c
3   a
4   d
4   d
4   e
4   f
5   g

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



<    1   2   3   4