Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi i am a beginner programmer and i was foolin around with
this program:
#!/usr/bin/perl print "What file do you want to \"detabify?\" "; $file=<>; chomp $file; $/=undef; open FILE, "<$file"; $text=<FILE>; close FILE; $text=~s/\t/ /g; open FILE, ">$file"; print $text; close FILE;
and i was woundering how you would goet it to read from a
text file and change all the letter J's to P's.
i tryed using this: $text=~s/j/p/;
but it would only change the first letter J...
Could someone please help me with this....

Replies are listed 'Best First'.
Re: Substitution Operator
by blakem (Monsignor) on Aug 28, 2001 at 11:57 UTC
    If you are just wanting to substitute a single letter, the above tr solution is recommended. However, if you wanted to replace an entire string throughout your $text variable, you'd want to use the s///g construct.

    Since this also works for single letters, a slightly less optimized solution than tr/j/p/ is:

    $text =~ s/j/p/g;
    Your code could also benefit from use strict; which will help you practice good coding style, and taint checking which will help you realize the inherant insecurities of passing user input directly to system calls.

    -Blake

Re: Substitution Operator
by bwana147 (Pilgrim) on Aug 28, 2001 at 11:52 UTC
    perl -pi.bak -e 'tr/j/p/' myfile

    Read perlrun to learn everything there is to know about perl's command-line arguments, and perlop for the details about the transliteration operator tr

    --bwana147

Re: Substitution Operator
by Chady (Priest) on Aug 28, 2001 at 12:29 UTC

    ...moreover, you are not reading the whole file, you are just reading the first line.. the <FILEHANDLE> operator returns a single line if it is expected to return a scalar, and a list in list context.. so to read all your file, you must read it into an array: @lines = <FILE>; then iterate over that array..

    The array is split with the $/ variable. which is \n by default.. you can undef this variable to read the whole file as a single string.

    { local $/; $text = <FILE>; }
    this will read all the text into a single variable...

    you should look into what solution suits you better.


    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/
Re: Substitution Operator
by Zecho (Hermit) on Aug 28, 2001 at 12:50 UTC
    perlman:perlop is a great place to start, it describes the s/// function in detail.. If you really want to learn the ins and outs I recommend bookmarking it and studying it.

    update: changed to[id:] link for cookie's sake