Newbie Questions: Swithing from Perl to Python

Roy Smith roy at panix.com
Sat Oct 25 22:13:25 EDT 2003


In article <jEEmb.37394$RP2.27641 at twister.tampabay.rr.com>,
 "Luther Barnum" <SpamSucks at rr.com> wrote:

> I am a new Python programmer and I am having a few difficulties. I love Perl
> and I am just trying to learn Python because it is used heavily at work. It
> looks pretty cool so I am diving in. I'm sure they are easy but I not sure
> how to proceed.

Check out the library reference at

http://www.python.org/doc/current/lib/lib.html

> 1. How can I run a program and modify the output on the fly then send it to
> standard output.
> 
> Example in Perl:
> 
> ex. open(LS_PIPE, "/usr/bin/ls |");
>      while(<LS_PIPE>) {
>      s/this/that/g;
>      print;
>      }
>      close(LS_PIPE);

Take a look at the popen2 module for the pipe functionality.  The "while 
(<LS_PIPE>)" is handled by readlines(), or just iterating over a file 
(read the reference manual and/or tutorial on file objects).  The re 
module gets you perl-like regular expressions.

On the other hand, the dircache and os.path modules provides simplier 
ways to iterate over a list of filenames in a directory.
 
> 2. How can I sort and print out a hash.
> 
> Example in Perl:
> 
> ex. foreach $string (sort keys %hash) {
>      print("$string = $hash{$string}\n");
>      }
> 
> In Perl these are very easy tasks, but I am finding it a little difficult to
> understand.

The Python version of a hash is called a dictionary.  For the above, you 
want to do something along the lines of:

keys = myDict.keys()
keys.sort()
for key in keys:
   print "%s = %s" % (key, myDict[key])

If you come from a Perl background, it may take a while to get used to 
the Pythonic way of doing things, but it'll start to make sense quickly.




More information about the Python-list mailing list