Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

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!/!!);


Comment on perl one liner
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 (Canon) 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 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.

      Cheers,

      JohnGG

      Update: Added my declarations to second code snippet.

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 :-))

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://754952]
Approved by jettero
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (11)
As of 2014-09-02 17:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (26 votes), past polls