[31365] in Perl-Users-Digest

home help back first fref pref prev next nref lref last post

Perl-Users Digest, Issue: 2617 Volume: 11

daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Thu Oct 1 18:09:45 2009

Date: Thu, 1 Oct 2009 15:09:10 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)

Perl-Users Digest           Thu, 1 Oct 2009     Volume: 11 Number: 2617

Today's topics:
        FAQ 4.54 Why does defined() return true on empty arrays <brian@theperlreview.com>
        FAQ 5.39 Why do I get weird spaces when I print an arra <brian@theperlreview.com>
        FAQ 7.3 Do I always/never have to quote my strings or u <brian@theperlreview.com>
        FAQ 8.12 How do I start a process in the background? <brian@theperlreview.com>
        FAQ 8.2 How come exec() doesn't return? <brian@theperlreview.com>
        FAQ 8.28 How can I call backticks without shell process <brian@theperlreview.com>
        FAQ 9.22 How do I read mail? <brian@theperlreview.com>
        machine dependent left shift results <sorry@nospam.com>
        Q: sort's key and cmp parameters <gb345@invalid.com>
    Re: Q: sort's key and cmp parameters <no.email@please.post>
        scope subroutine argument with "our" <pmacadam@gmail.com>
    Re: scope subroutine argument with "our" <uri@StemSystems.com>
        SR xtimes <julia_2683@hotmail.com>
    Re: SR xtimes <tadmc@seesig.invalid>
    Re: SR xtimes <julia_2683@hotmail.com>
    Re: SR xtimes <jimsgibson@gmail.com>
    Re: SR xtimes <jimsgibson@gmail.com>
    Re: SR xtimes <kst-u@mib.org>
    Re: SR xtimes <houda.araj@gmail.com>
    Re: SR xtimes <tadmc@seesig.invalid>
        Web-based two-column diff with color <s1037989@gmail.com>
    Re: Web-based two-column diff with color <tadmc@seesig.invalid>
        Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)

----------------------------------------------------------------------

Date: Wed, 30 Sep 2009 09:59:58 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 4.54 Why does defined() return true on empty arrays and hashes?
Message-Id: <y_Fwm.13805$kC.5517@newsfe11.iad>

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to 
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

4.54: Why does defined() return true on empty arrays and hashes?

    The short story is that you should probably only use defined on scalars
    or functions, not on aggregates (arrays and hashes). See "defined" in
    perlfunc in the 5.004 release or later of Perl for more detail.



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in 
perlfaq.pod.


------------------------------

Date: Thu, 01 Oct 2009 10:00:01 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 5.39 Why do I get weird spaces when I print an array of lines?
Message-Id: <B4%wm.17113$Fg7.8667@newsfe03.iad>

This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to 
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

5.39: Why do I get weird spaces when I print an array of lines?

    (contributed by brian d foy)

    If you are seeing spaces between the elements of your array when you
    print the array, you are probably interpolating the array in double
    quotes:

            my @animals = qw(camel llama alpaca vicuna);
            print "animals are: @animals\n";

    It's the double quotes, not the "print", doing this. Whenever you
    interpolate an array in a double quote context, Perl joins the elements
    with spaces (or whatever is in $", which is a space by default):

            animals are: camel llama alpaca vicuna

    This is different than printing the array without the interpolation:

            my @animals = qw(camel llama alpaca vicuna);
            print "animals are: ", @animals, "\n";

    Now the output doesn't have the spaces between the elements because the
    elements of @animals simply become part of the list to "print":

            animals are: camelllamaalpacavicuna

    You might notice this when each of the elements of @array end with a
    newline. You expect to print one element per line, but notice that every
    line after the first is indented:

            this is a line
             this is another line
             this is the third line

    That extra space comes from the interpolation of the array. If you don't
    want to put anything between your array elements, don't use the array in
    double quotes. You can send it to print without them:

            print @lines;



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in 
perlfaq.pod.


------------------------------

Date: Thu, 01 Oct 2009 16:00:02 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 7.3 Do I always/never have to quote my strings or use semicolons and commas?
Message-Id: <6m4xm.245934$0e4.71863@newsfe19.iad>

This is an excerpt from the latest version perlfaq7.pod, which
comes with the standard Perl distribution. These postings aim to 
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

7.3: Do I always/never have to quote my strings or use semicolons and commas?

    Normally, a bareword doesn't need to be quoted, but in most cases
    probably should be (and must be under "use strict"). But a hash key
    consisting of a simple word (that isn't the name of a defined
    subroutine) and the left-hand operand to the "=>" operator both count as
    though they were quoted:

            This                    is like this
            ------------            ---------------
            $foo{line}              $foo{'line'}
            bar => stuff            'bar' => stuff

    The final semicolon in a block is optional, as is the final comma in a
    list. Good style (see perlstyle) says to put them in except for
    one-liners:

            if ($whoops) { exit 1 }
            @nums = (1, 2, 3);

            if ($whoops) {
                    exit 1;
            }

            @lines = (
            "There Beren came from mountains cold",
            "And lost he wandered under leaves",
            );



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in 
perlfaq.pod.


------------------------------

Date: Wed, 30 Sep 2009 22:00:02 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 8.12 How do I start a process in the background?
Message-Id: <CxQwm.11408$ma7.3954@newsfe04.iad>

This is an excerpt from the latest version perlfaq8.pod, which
comes with the standard Perl distribution. These postings aim to 
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

8.12: How do I start a process in the background?

    (contributed by brian d foy)

    There's not a single way to run code in the background so you don't have
    to wait for it to finish before your program moves on to other tasks.
    Process management depends on your particular operating system, and many
    of the techniques are in perlipc.

    Several CPAN modules may be able to help, including IPC::Open2 or
    IPC::Open3, IPC::Run, Parallel::Jobs, Parallel::ForkManager, POE,
    Proc::Background, and Win32::Process. There are many other modules you
    might use, so check those namespaces for other options too.

    If you are on a unix-like system, you might be able to get away with a
    system call where you put an "&" on the end of the command:

            system("cmd &")

    You can also try using "fork", as described in perlfunc (although this
    is the same thing that many of the modules will do for you).

    STDIN, STDOUT, and STDERR are shared
        Both the main process and the backgrounded one (the "child" process)
        share the same STDIN, STDOUT and STDERR filehandles. If both try to
        access them at once, strange things can happen. You may want to
        close or reopen these for the child. You can get around this with
        "open"ing a pipe (see "open" in perlfunc) but on some systems this
        means that the child process cannot outlive the parent.

    Signals
        You'll have to catch the SIGCHLD signal, and possibly SIGPIPE too.
        SIGCHLD is sent when the backgrounded process finishes. SIGPIPE is
        sent when you write to a filehandle whose child process has closed
        (an untrapped SIGPIPE can cause your program to silently die). This
        is not an issue with "system("cmd&")".

    Zombies
        You have to be prepared to "reap" the child process when it
        finishes.

                $SIG{CHLD} = sub { wait };

                $SIG{CHLD} = 'IGNORE';

        You can also use a double fork. You immediately wait() for your
        first child, and the init daemon will wait() for your grandchild
        once it exits.

                unless ($pid = fork) {
                    unless (fork) {
                        exec "what you really wanna do";
                        die "exec failed!";
                    }
                    exit 0;
                }
                waitpid($pid, 0);

        See "Signals" in perlipc for other examples of code to do this.
        Zombies are not an issue with "system("prog &")".



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in 
perlfaq.pod.


------------------------------

Date: Thu, 01 Oct 2009 22:00:02 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 8.2 How come exec() doesn't return?
Message-Id: <CD9xm.18983$Fg7.3701@newsfe03.iad>

This is an excerpt from the latest version perlfaq8.pod, which
comes with the standard Perl distribution. These postings aim to 
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

8.2: How come exec() doesn't return?

    (contributed by brian d foy)

    The "exec" function's job is to turn your process into another command
    and never to return. If that's not what you want to do, don't use
    "exec". :)

    If you want to run an external command and still keep your Perl process
    going, look at a piped "open", "fork", or "system".



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in 
perlfaq.pod.


------------------------------

Date: Wed, 30 Sep 2009 16:00:02 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 8.28 How can I call backticks without shell processing?
Message-Id: <6gLwm.1580$QG1.209@newsfe23.iad>

This is an excerpt from the latest version perlfaq8.pod, which
comes with the standard Perl distribution. These postings aim to 
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

8.28: How can I call backticks without shell processing?

    This is a bit tricky. You can't simply write the command like this:

            @ok = `grep @opts '$search_string' @filenames`;

    As of Perl 5.8.0, you can use "open()" with multiple arguments. Just
    like the list forms of "system()" and "exec()", no shell escapes happen.

            open( GREP, "-|", 'grep', @opts, $search_string, @filenames );
            chomp(@ok = <GREP>);
            close GREP;

    You can also:

            my @ok = ();
            if (open(GREP, "-|")) {
                    while (<GREP>) {
                            chomp;
                            push(@ok, $_);
                    }
                    close GREP;
            } else {
                    exec 'grep', @opts, $search_string, @filenames;
            }

    Just as with "system()", no shell escapes happen when you "exec()" a
    list. Further examples of this can be found in "Safe Pipe Opens" in
    perlipc.

    Note that if you're using Windows, no solution to this vexing issue is
    even possible. Even if Perl were to emulate "fork()", you'd still be
    stuck, because Windows does not have an argc/argv-style API.



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in 
perlfaq.pod.


------------------------------

Date: Thu, 01 Oct 2009 04:00:02 GMT
From: PerlFAQ Server <brian@theperlreview.com>
Subject: FAQ 9.22 How do I read mail?
Message-Id: <6PVwm.454946$Ta5.443833@newsfe15.iad>

This is an excerpt from the latest version perlfaq9.pod, which
comes with the standard Perl distribution. These postings aim to 
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

9.22: How do I read mail?

    While you could use the Mail::Folder module from CPAN (part of the
    MailFolder package) or the Mail::Internet module from CPAN (part of the
    MailTools package), often a module is overkill. Here's a mail sorter.

            #!/usr/bin/perl

            my(@msgs, @sub);
            my $msgno = -1;
            $/ = '';                    # paragraph reads
            while (<>) {
                    if (/^From /m) {
                            /^Subject:\s*(?:Re:\s*)*(.*)/mi;
                            $sub[++$msgno] = lc($1) || '';
                    }
                    $msgs[$msgno] .= $_;
            }
            for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
                    print $msgs[$i];
            }

    Or more succinctly,

            #!/usr/bin/perl -n00
            # bysub2 - awkish sort-by-subject
            BEGIN { $msgno = -1 }
            $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
            $msg[$msgno] .= $_;
            END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in 
perlfaq.pod.


------------------------------

Date: Thu, 1 Oct 2009 13:22:10 -0700
From: "easily_confused" <sorry@nospam.com>
Subject: machine dependent left shift results
Message-Id: <0040e1ce$1$32533$c3e8da3@news.astraweb.com>

On a 32 bit machine, ~0<<32 gives 11111111111111111111111111111111  (I was
expecting 0)

(~0<<31)<<1 gives 0.

I was trying ~(~0<<$size) to create a mask of $size ones.

((1<<$size) -1) was what I tried first but it also failed for the same
reason, I guess.

I like that in verilog I can just say {$size{1'b1}}

I know I can use Math::BigInt, but I still wonder what the rationale is
behind the first example failing.

EC




------------------------------

Date: Thu, 1 Oct 2009 17:04:01 +0000 (UTC)
From: gb345 <gb345@invalid.com>
Subject: Q: sort's key and cmp parameters
Message-Id: <ha2ne1$soa$1@reader1.panix.com>





Challenge: to come up with a sorting task that cannot be achieved
by passing to the sort method (or sorted function) suitable values
for its key and reverse parameters, but instead *require* giving
a value to its cmp parameter.

For example,

from random import random
scrambled = some_list.sort(cmp=lambda x, y: cmp(random(), 0.5))

can be achieved (to a very good approximation at least) with

scrambled = some_list.sort(key=lambda x: random())

Is there a real-life sorting task that requires (or is far more
efficient with) cmp and can't be easily achieved with key and
reverse?

Many thanks in advance,

G.

P.S. I guess that, if sort is going to produce a non-trivial,
*consistent* order, a function CMP passed as the value of its cmp
parameter must satisfy the following properties:

0. CMP(x, y) must be non-zero for some elements x, y of the list; 
1. anti-symmetry: sign(CMP(x, y)) must be equal to -sign(CMP(y, x));
2. transitivity: if sign(CMP(x, y)) equals sign(CMP(y, z)), then
   sign(CMP(x, z)) must be equal to sign(CMP(x, y)).

In (1) and (2), sign() stands for the function

            -1 if x  < 0
  sign(x) =  0 if x == 0
             1 if x  > 0

I suppose that all bets are off if these properties are not satisfied,
though the documentation does not make this entirely clear, as far
as I can tell.  (If I'm wrong about this alleged omission, please
point me to the part of the docs that I missed.)


------------------------------

Date: Thu, 1 Oct 2009 17:05:40 +0000 (UTC)
From: kj <no.email@please.post>
Subject: Re: Q: sort's key and cmp parameters
Message-Id: <ha2nh3$2l3$1@reader1.panix.com>



My apologies!

Please disregard this post.  I sent it to the wrong newsgroup.

G.

In <ha2ne1$soa$1@reader1.panix.com> gb345 <gb345@invalid.com> writes:

>Challenge: to come up with a sorting task that cannot be achieved
>by passing to the sort method (or sorted function) suitable values
>for its key and reverse parameters, but instead *require* giving
>a value to its cmp parameter.

>For example,

>from random import random
>scrambled = some_list.sort(cmp=lambda x, y: cmp(random(), 0.5))

>can be achieved (to a very good approximation at least) with

>scrambled = some_list.sort(key=lambda x: random())

>Is there a real-life sorting task that requires (or is far more
>efficient with) cmp and can't be easily achieved with key and
>reverse?

>Many thanks in advance,

>G.

>P.S. I guess that, if sort is going to produce a non-trivial,
>*consistent* order, a function CMP passed as the value of its cmp
>parameter must satisfy the following properties:

>0. CMP(x, y) must be non-zero for some elements x, y of the list; 
>1. anti-symmetry: sign(CMP(x, y)) must be equal to -sign(CMP(y, x));
>2. transitivity: if sign(CMP(x, y)) equals sign(CMP(y, z)), then
>   sign(CMP(x, z)) must be equal to sign(CMP(x, y)).

>In (1) and (2), sign() stands for the function

>            -1 if x  < 0
>  sign(x) =  0 if x == 0
>             1 if x  > 0

>I suppose that all bets are off if these properties are not satisfied,
>though the documentation does not make this entirely clear, as far
>as I can tell.  (If I'm wrong about this alleged omission, please
>point me to the part of the docs that I missed.)


------------------------------

Date: Thu, 1 Oct 2009 12:36:06 -0700 (PDT)
From: pacmac <pmacadam@gmail.com>
Subject: scope subroutine argument with "our"
Message-Id: <d10ece08-661e-4837-b04d-89a84818dc76@b25g2000prb.googlegroups.com>

Hello All,

I'm trying to understand someone else's code. It's a mod_perl
PerlAccessHandler.

I'm not sure what's accomplished by "our" scoping an already-our-
scoped variable when passed as an argument to a subroutine. See the
way check_pwd() is called below. Does doing this make a copy? I don't
get it.

Can someone please enlighten me?
PM

package myControl;

use strict;

use [typical Apache2 modules];

our $PWD_SECRET = '128XYZ345';

sub handler {
  my $r = shift;
  ...
  my ($stat, $msg) = check_pwd($r, our $PWD_SECRET);
  ...
}

sub check_pwd {
  my $r = shift;
  my $secret = shift;

  ... do stuff ...
  return (1, 'OK');
}


------------------------------

Date: Thu, 01 Oct 2009 16:42:01 -0400
From: "Uri Guttman" <uri@StemSystems.com>
Subject: Re: scope subroutine argument with "our"
Message-Id: <87vdiyhmna.fsf@quad.sysarch.com>

>>>>> "p" == pacmac  <pmacadam@gmail.com> writes:

  p> I'm not sure what's accomplished by "our" scoping an already-our-
  p> scoped variable when passed as an argument to a subroutine. See the
  p> way check_pwd() is called below. Does doing this make a copy? I don't
  p> get it.

  p> package myControl;

  p> our $PWD_SECRET = '128XYZ345';

  p> sub handler {
  p>   my $r = shift;
  p>   ...
  p>   my ($stat, $msg) = check_pwd($r, our $PWD_SECRET);
  p>   ...
  p> }

AFAIK it doesn't do anything special. the outer our is file scoped so
the inner one is redundant. both will refer to the same package
variable. the coder probably didn't understand the scoping rules of our
and thought our needed to be used in front of each use of that
variable. it only needs to be used the first time in a given scope.

uri

-- 
Uri Guttman  ------  uri@stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------


------------------------------

Date: Thu, 1 Oct 2009 08:46:31 -0700 (PDT)
From: julia <julia_2683@hotmail.com>
Subject: SR xtimes
Message-Id: <8fe74ddc-925b-444a-a3c2-3c64d3904587@d34g2000vbm.googlegroups.com>

How to make this command search and replace xtimes.
perl -p -i -e 's/oldstring/newstring/g' file.txt

Thanks


------------------------------

Date: Thu, 01 Oct 2009 10:52:12 -0500
From: Tad J McClellan <tadmc@seesig.invalid>
Subject: Re: SR xtimes
Message-Id: <slrnhc9j6k.ldl.tadmc@tadmc30.sbcglobal.net>

julia <julia_2683@hotmail.com> wrote:
> How to make this command search and replace xtimes.
> perl -p -i -e 's/oldstring/newstring/g' file.txt


That depends on what "xtimes" means.

What does "xtimes" mean when you say it?

xtimes per line?

xtimes per file?

x lines per file?

 ...?


-- 
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"


------------------------------

Date: Thu, 1 Oct 2009 11:17:19 -0700 (PDT)
From: julia <julia_2683@hotmail.com>
Subject: Re: SR xtimes
Message-Id: <b6257e51-5a88-48cb-954e-77463a36546b@s6g2000vbp.googlegroups.com>

On 1 oct, 11:52, Tad J McClellan <ta...@seesig.invalid> wrote:
> julia <julia_2...@hotmail.com> wrote:
> > How to make this command search and replace xtimes.
> > perl -p -i -e 's/oldstring/newstring/g' file.txt
>
> That depends on what "xtimes" means.
>
> What does "xtimes" mean when you say it?
>
> xtimes per line?
>
> xtimes per file?
>
> x lines per file?
>
> ...?
>
> --
> Tad McClellan
> email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"

I want to take 4times oldstring and replace it with newstring1
I want to take 3times oldstring and replace it with newstring2
oldstring
oldstring
oldstring
oldstring
oldstring
oldstring

newstring1
newstring1
newstring1
newstring1
newstring2
newstring2
newstring2

Thanks for your help


------------------------------

Date: Thu, 01 Oct 2009 11:56:58 -0700
From: Jim Gibson <jimsgibson@gmail.com>
Subject: Re: SR xtimes
Message-Id: <011020091156581241%jimsgibson@gmail.com>

In article
<b6257e51-5a88-48cb-954e-77463a36546b@s6g2000vbp.googlegroups.com>,
julia <julia_2683@hotmail.com> wrote:

> On 1 oct, 11:52, Tad J McClellan <ta...@seesig.invalid> wrote:
> > julia <julia_2...@hotmail.com> wrote:
> > > How to make this command search and replace xtimes.
> > > perl -p -i -e 's/oldstring/newstring/g' file.txt
> >
> > That depends on what "xtimes" means.
> >
> > What does "xtimes" mean when you say it?
> >
> > xtimes per line?
> >
> > xtimes per file?
> >
> > x lines per file?

> I want to take 4times oldstring and replace it with newstring1
> I want to take 3times oldstring and replace it with newstring2
> oldstring
> oldstring
> oldstring
> oldstring
> oldstring
> oldstring
> 
> newstring1
> newstring1
> newstring1
> newstring1
> newstring2
> newstring2
> newstring2

perl -p -e 's/oldstring/($.<5?"newstring1":"newstring2")/e;' file.txt

This uses the $. variable that gives the line number in the input file
and the e modifier to the substitute operator that cause the
replacement string to be evaluated as a Perl expression.

Note that this only works if oldstring appears on every line. If that
is not the case, then you have to use a counter that counts how many
times a match has occurred and modify your replacement string
accordingly.

-- 
Jim Gibson


------------------------------

Date: Thu, 01 Oct 2009 12:14:13 -0700
From: Jim Gibson <jimsgibson@gmail.com>
Subject: Re: SR xtimes
Message-Id: <011020091214130411%jimsgibson@gmail.com>

In article <011020091156581241%jimsgibson@gmail.com>, Jim Gibson
<jimsgibson@gmail.com> wrote:


> perl -p -e 's/oldstring/($.<5?"newstring1":"newstring2")/e;' file.txt
> 
> This uses the $. variable that gives the line number in the input file
> and the e modifier to the substitute operator that cause the
> replacement string to be evaluated as a Perl expression.
> 
> Note that this only works if oldstring appears on every line. If that
> is not the case, then you have to use a counter that counts how many
> times a match has occurred and modify your replacement string
> accordingly.

In the latter case the following should work:

perl -p -e 's/oldstring/(++$n<5?"newstring1":"newstring2")/e;' file.txt

-- 
Jim Gibson


------------------------------

Date: Thu, 01 Oct 2009 13:08:05 -0700
From: Keith Thompson <kst-u@mib.org>
Subject: Re: SR xtimes
Message-Id: <lnab0aop22.fsf@nuthaus.mib.org>

julia <julia_2683@hotmail.com> writes:
> On 1 oct, 11:52, Tad J McClellan <ta...@seesig.invalid> wrote:
>> julia <julia_2...@hotmail.com> wrote:
>> > How to make this command search and replace xtimes.
>> > perl -p -i -e 's/oldstring/newstring/g' file.txt
>>
>> That depends on what "xtimes" means.
>>
>> What does "xtimes" mean when you say it?
>>
>> xtimes per line?
>>
>> xtimes per file?
>>
>> x lines per file?
>>
>> ...?
>>
>> --
>> Tad McClellan
>> email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"
>
> I want to take 4times oldstring and replace it with newstring1
> I want to take 3times oldstring and replace it with newstring2
> oldstring
> oldstring
> oldstring
> oldstring
> oldstring
> oldstring
>
> newstring1
> newstring1
> newstring1
> newstring1
> newstring2
> newstring2
> newstring2

What if oldstring appears more than once on a line?

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"


------------------------------

Date: Thu, 1 Oct 2009 13:20:36 -0700 (PDT)
From: houda <houda.araj@gmail.com>
Subject: Re: SR xtimes
Message-Id: <42750906-f442-422b-a60a-c33fdf6f70d8@d23g2000vbm.googlegroups.com>

On 1 oct, 16:08, Keith Thompson <ks...@mib.org> wrote:
> julia <julia_2...@hotmail.com> writes:
> > On 1 oct, 11:52, Tad J McClellan <ta...@seesig.invalid> wrote:
> >> julia <julia_2...@hotmail.com> wrote:
> >> > How to make this command search and replace xtimes.
> >> > perl -p -i -e 's/oldstring/newstring/g' file.txt
>
> >> That depends on what "xtimes" means.
>
> >> What does "xtimes" mean when you say it?
>
> >> xtimes per line?
>
> >> xtimes per file?
>
> >> x lines per file?
>
> >> ...?
>
> >> --
> >> Tad McClellan
> >> email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"
>
> > I want to take 4times oldstring and replace it with newstring1
> > I want to take 3times oldstring and replace it with newstring2
> > oldstring
> > oldstring
> > oldstring
> > oldstring
> > oldstring
> > oldstring
>
> > newstring1
> > newstring1
> > newstring1
> > newstring1
> > newstring2
> > newstring2
> > newstring2
>
> What if oldstring appears more than once on a line?
>
> --
> Keith Thompson (The_Other_Keith) ks...@mib.org =A0<http://www.ghoti.net/~=
kst>
> Nokia
> "We must do something. =A0This is something. =A0Therefore, we must do thi=
s."
> =A0 =A0 -- Antony Jay and Jonathan Lynn, "Yes Minister"

I am sorry not being clear.
This RE takes only the first part of RE (Search)
perl -p -e 's/\{\}\&\{\}/($.<5?"{newstring1}":"{newstring2}")/e;'
text.txt

My old string can appear more than one time.
(oldstring)(oldstring)(oldstring) replaced by (newstring1)(newstring2)
(newstring1)
Many Thanks



------------------------------

Date: Thu, 01 Oct 2009 16:57:37 -0500
From: Tad J McClellan <tadmc@seesig.invalid>
Subject: Re: SR xtimes
Message-Id: <slrnhca8jo.pic.tadmc@tadmc30.sbcglobal.net>

houda <houda.araj@gmail.com> wrote:

>> julia <julia_2...@hotmail.com> writes:

> I am sorry not being clear.


Are you "julia" or are you "houda"?

Please choose one posting address and stick with it.


-- 
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"


------------------------------

Date: Thu, 1 Oct 2009 12:25:33 -0700 (PDT)
From: Stefan <s1037989@gmail.com>
Subject: Web-based two-column diff with color
Message-Id: <1c5bc245-bcda-4182-9dd2-2db0bb3ffc3c@j19g2000yqk.googlegroups.com>

I wrote a Perl script that is too simple to create a project for, but
I do want to share it in case anyone might have use.  For me, I use it
to upload two Cisco config scripts and quickly see the difference
between the two.  Use and modify as you will.  It's public domain.

The diff command is:
diff -iwBay -W $W --left-column file1 file2

Where $W is 10 + 2 * maxlen using the output of:
wc -L file1 file2

# cat diff.cgi
#!/usr/bin/perl

use strict;
use warnings;
use CGI;

my $Q = new CGI;
print "Content-type: text/html\n\n";
if ( !$Q->param('old') && !$Q->param('new') ) {
	print <<'	FORM';
	<FORM ENCTYPE="multipart/form-data" ACTION="#" METHOD="POST">
	Please select older file:<BR>
	<INPUT TYPE="FILE" NAME="old"><p>
	Please select newer file:<BR>
	<INPUT TYPE="FILE" NAME="new"><p>
	<INPUT TYPE="submit">
	</FORM>
	FORM
} else {
	my $oldfile = $Q->param('old');
	open OLD, ">/tmp/diff.old.$$";
	while ( <$oldfile> ) {
		print OLD;
	}
	close OLD;
	my $newfile = $Q->param('new');
	open NEW, ">/tmp/diff.new.$$";
	while ( <$newfile> ) {
		print NEW;
	}
	close NEW;
	print "<html>\n";
	print "<head>\n";
	print "<style type=\"text/css\">\n\ttd.delete { color: red; }\n
\ttd.add { color: green; }\n\ttd.change { color: blue; }\n\ttd.common
{ color: black; }\n</style>\n";
	print "</head>\n";
	my $maxlen = 0;
	foreach ( qx{wc -L "/tmp/diff.old.$$" "/tmp/diff.new.$$"} ) {
		/^\s*(\d+)\s+/;
		$maxlen = $1 if $1 > $maxlen;
	}
	my $W = $maxlen * 2 + 10;
	print "<body>\n";
	print "<table>\n";
	foreach ( qx{diff -iwBay -W $W --left-column "/tmp/diff.old.$$" "/tmp/
diff.new.$$"} ) {
		my ($old, $sym, $new);
		if ( /^(.*?)\s+([\|\>])\t(.*?)$/ ) {
			($old, $sym, $new) = (/^(.*?)\s+([\|\>])\t(.*?)$/);
		} elsif ( /^(.*?)\s+([\<\(])$/ ) {
			($old, $sym) = (/^(.*?)\s+([\<\(])$/);
		}
		print "<tr>";
		if ( $sym eq '<' ) {
			if ( $old && !$new ) {
				print "<td class=\"delete\">$old</td><td class=\"delete\">$sym</
td><td>&nbsp;</td>";
			} else {
				print "ERROR";
			}
		} elsif ( $sym eq '>' ) {
			if ( !$old && $new ) {
				print "<td>&nbsp;</td><td class=\"add\">$sym</td><td class=\"add\">
$new</td>";
			} else {
				print "ERROR";
			}
		} elsif ( $sym eq '|' ) {
			if ( $old && $new ) {
				print "<td class=\"change\">$old</td><td class=\"change\">$sym</
td><td class=\"change\">$new</td>";
			} else {
				print "ERROR";
			}
		} elsif ( $sym eq '(' ) {
			if ( $old && !$new ) {
				print "<td class=\"common\">$old</td><td class=\"common\">=</
td><td class=\"common\">$old</td>";
			} else {
				print "ERROR";
			}
		}
		print "</tr>\n";
	}
	print "</table>\n";
	print "</body>\n";
	print "</html>\n";
}


------------------------------

Date: Thu, 01 Oct 2009 17:06:00 -0500
From: Tad J McClellan <tadmc@seesig.invalid>
Subject: Re: Web-based two-column diff with color
Message-Id: <slrnhca93f.pic.tadmc@tadmc30.sbcglobal.net>

Stefan <s1037989@gmail.com> wrote:


> 	open OLD, ">/tmp/diff.old.$$";


You should always, yes *always*, check the return value from open():

    open OLD, ">/tmp/diff.old.$$" 
        or die "could not open '/tmp/diff.old.$$' $!";

The modern way to do it is to use the 3-arg form of open() along with
a lexical filehandle:

    open my $OLD, '>', "/tmp/diff.old.$$" 
        or die "could not open '/tmp/diff.old.$$' $!";


-- 
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/"


------------------------------

Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin) 
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>


Administrivia:

To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.

Back issues are available via anonymous ftp from
ftp://cil-www.oce.orst.edu/pub/perl/old-digests. 

#For other requests pertaining to the digest, send mail to
#perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
#sending perl questions to the -request address, I don't have time to
#answer them even if I did know the answer.


------------------------------
End of Perl-Users Digest V11 Issue 2617
***************************************


home help back first fref pref prev next nref lref last post