Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove a space from a perl variable

I am having a lot of trouble doing a simple search and replace. I tried the solution offered in How do I remove white space in a Perl string? but was unable to print this.

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 a couple of different ways, but I was unable to do this.

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

like image 572
M Alhassan Avatar asked Jun 26 '13 20:06

M Alhassan


1 Answers

You're almost there; you're just confused about operator precedence. The code you want to use is:

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

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

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

Because the bind operator =~ has higher precedence than 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 is 1 in this case) to the variable $hello_nospaces.

like image 108
mob Avatar answered Nov 02 '22 23:11

mob