Remove space from perl variable

I have a lot of trouble doing a simple search and replace. I tried the solution suggested in How to remove a space in a Perl string? but could not print it.

Here is my sample code:

#!/usr/bin/perl use strict; my $hello = "hello world"; print "$hello\n"; #this should print out >> hello world #now i am trying to print out helloworld (space removed) my $hello_nospaces = $hello =~ s/\s//g; #my $hello_nospaces = $hello =~ s/hello world/helloworld/g; #my $hello_nospaces = $hello =~ s/\s+//g; print "$hello_nospaces\n" #am getting a blank response when i run this. 

I tried several different ways, but I could not do it.

My end result is to automate some aspects of moving files in a linux environment, but sometimes files have spaces in the name, so I want to remove the space from this variable.

+7
source share
4 answers

You're almost there; you are simply confused about operator priority. The code you want to use:

 (my $hello_nospaces = $hello) =~ s/\s//g; 

First, this sets the $hello variable to the value of the $hello_nospaces variable. Then it performs a lookup operation on $hello_nospaces , as if you said

 my $hello_nospaces = $hello; $hello_nospaces =~ s/\s//g; 

Since the bind operator =~ takes precedence over the assignment operator = , the way you wrote it

 my $hello_nospaces = $hello =~ s/\s//g; 

first performs the substitution on $hello , and then assigns the result of the substitution operation (which in this case is 1) to the variable $hello_nospaces .

+19
source

Starting with 5.14 , Perl provides a non-destructive s/// option :

Nondestructive substitution

The substitution ( s/// ) and transliteration ( y/// ) operators now support the /r option, which copies the input variable, performs the substitution in the copy, and returns the result. The original remains unmodified.

 my $old = "cat"; my $new = $old =~ s/cat/dog/r; # $old is "cat" and $new is "dog" 

This is especially useful for map . See perlop .

So:

 my $hello_nospaces = $hello =~ s/\s//gr; 

should do what you want.

+8
source

You just need to add parentheses so that the Perl parser can figure out what you want.

 my $hello = "hello world"; print "$hello\n"; 

to

 (my $hello_nospaces = $hello) =~ s/\s//g; print "$hello_nospaces\n"; ## prints ## hello world ## helloworld 
+4
source

Separate this line:

 my $hello_nospaces = $hello =~ s/\s//g; 

In these two:

 my $hello_nospaces = $hello; $hello_nospaces =~ s/\s//g; 

From the official Perl Regex Tutorial :

If there is a match, s /// returns the number of substitutions made; otherwise, it returns false.

+3
source

All Articles