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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With