Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

perl one liner

by selva (Scribe)
on Apr 02, 2009 at 13:35 UTC ( #754952=perlquestion: print w/replies, xml ) Need Help??
selva has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks ,

How to substitute and store the result in different variable in the same line .

Ex : $var1 = "10/02/2009";

I have to remove the "/" in the above variable and store in to different variable .

I tried following one , but it is returning substitution status only.

($var2) = ( $var1 =~ s!/!!);

Replies are listed 'Best First'.
Re: perl one liner
by lakshmananindia (Chaplain) on Apr 02, 2009 at 13:40 UTC

    Try to use the following

    ($var2=$var1) =~ s/\///g;
    --Lakshmanan G.

    The great pleasure in my life is doing what people say you cannot do.

Re: perl one liner
by moritz (Cardinal) on Apr 02, 2009 at 13:41 UTC
    The trick is to assign it first, and then substitute it only on the second variable.
    $ perl -E '$var1 = "10/02/2009"; ($var2 = $var1) =~ s{/}{}g; say $var2 +' 10022009
Re: perl one liner
by eff_i_g (Curate) on Apr 02, 2009 at 13:41 UTC
    Almost. You need to do the substitution after the assignment, not assign the results of the substitution:

    ($var2 = $var1) =~ s!/!!;
Re: perl one liner
by shmem (Chancellor) on Apr 02, 2009 at 13:42 UTC

    Do the assignment and substitute thereafter:

    ($var2 = $var1) =~ s!/!!;

    The substitution above operates on $var2.

Re: perl one liner
by Bloodnok (Vicar) on Apr 02, 2009 at 14:28 UTC
    The majority of the other answers illustrate the answer (varying only in the RE delimiters) to be found in recipe 6.1 of the Perl Cookbook.

    I'd strongly recommend you purchase a copy...

    A user level that continues to overstate my experience :-))
Re: perl one liner
by irah (Pilgrim) on Apr 02, 2009 at 13:43 UTC
    my ($day,$month,$year) = split("/",$date);
      my ($day,$month,$year) = split("/",$date);

      I think that code is answering a different question, but you could have answered the OP's one by adding a join.

      my $var1 = q{10/02/2009}; my $var2 = join q{}, split m{/}, $var1;

      Another way would be to use tr, for details look in Quote Like Operators;

      my $var1 = q{10/02/2009}; ( my $var2 = $var1 ) =~ tr{/}{}d;

      I hope this is of interest.



      Update: Added my declarations to second code snippet.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://754952]
Approved by jettero
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2017-12-16 20:49 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (459 votes). Check out past polls.