views:

216

answers:

3

I tried removing all newlines (\n) from the values of a hash:

my %var_h = (  "ID"   => " This is Test 
                           This is new line TEST 


                           newline Test end ");

How can I remove all the new lines from the values of %var_h?

I tried s/\\n//g but I could not get it to work.

+4  A: 

What are you running the substitution against? You seem to want to fix only the values, so I would use the values keyword:

for my $value (values %var_h) {
  $value =~ s/\n//g;
}

An alternative (at OP's request) would be to use map and a slice though I find it a lot less clear:

@var_h{keys %var_h} = map { s/\n//g } values %var_h;
Telemachus
With hash value ..
joe
is there any other to way to do this
joe
I added a second method. But do you want a method without using `values` at all?
Telemachus
@var_h{values %var_h} needs to be @var_h{keys %var_h} - also, I'm not sure if keys and values are guaranteed to return in the same ordering...
ijw
@ ijw - Stupid of me, thanks for the catch. I believe that they return in the same order, but I will have to check that.
Telemachus
@ ijw - keys, values and each are guaranteed to return in the same order. See perldoc -f values|keys|each
Telemachus
+13  A: 
s:\n::g for values %var_h;

should do the trick.

Massa
+1 because statement modifiers exist for a reason ;-)
Sinan Ünür
I'm absolutely shocked that this works (in that values does not copy) but I just tested it with a simpler example.
Mark Canlas
@Unknown Google: yes, values does not copy and for will alias to them. keys does copy, though.
ysth
+3  A: 

All other solutions remove \n from all values of hash.

I'm not sure if this is required.

So to remove only from this one value you have:

$var_h{'ID'} =~ s/\r?\n//g;

Technically s/\n//g should be sufficient, but I have the habit of adding \r? before it, so it will handle Windows-styled new lines as well.

depesz
It's a good point. I was assuming that the one value was just an example and that he might not know in advance which values had or didn't have unwanted newlines.
Telemachus
How can the extra characters get in there?
Sinan Ünür
Elves? I didn't give much thought to _how_ the newlines got there. Off the top of my head: bad user input, a regular expression capture gone wrong, sheer cussedness and programmer error.
Telemachus
@Telemachus I am asking about the magical extra \r's. The OP's requirement was to remove \n's.
Sinan Ünür
@Sinan: Genuine Advantage Elves, in that case
Telemachus
Actually to be fully correct s/\r\n?|\n//g; i.e. \r\n, \r, \n
Brad Gilbert
Well, since both "\r" and "\n" can be replaced by '', then it's simpler to just write: s/[\r\n]+//g - it will work the same way.
depesz
or just y/\r\n//d
ysth