LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   setting new variable to regex of another without changing the other variable in perl (https://www.linuxquestions.org/questions/programming-9/setting-new-variable-to-regex-of-another-without-changing-the-other-variable-in-perl-920063/)

Eppo 12-22-2011 11:29 AM

setting new variable to regex of another without changing the other variable in perl
 
currently i have a Variable named $name which contains "JOHN,SMITH".
What i'm looking to do is take the first letter of the first and last name and assign it to another variable without changing $name.
what i tried was this:
Code:

$OF = $name =~ s/^(.).*,(.).*/$1$2/;
so what i'm getting is a value of 1 for $OF and name is changing to JS.
how do i get $OF to be JS and $name to stay "JOHN,SMITH"
thanks

Edit: figured it out:

Code:

($OF = $name) =~ s/^(.).*,(.).*/$1$2/;

markush 12-22-2011 02:35 PM

Hi Eppo,

it becomes more obvious what you want to achieve when you split the name at first and then use a regex for each word, here's the example:
Code:

#!/usr/bin/perl

use strict ;
use warnings ;

my $john = "John,Smith" ;

my @name = split ",", $john ;

my $name ;
foreach $name (@name) {
  $name =~ m/(^.)/ ;
  print $1 ;
}

Markus


All times are GMT -5. The time now is 03:40 AM.