简体   繁体   English

如何从哈希值中删除所有换行符?

[英]How can I remove all newlines from hash values?

I tried removing all newlines ( \\n ) from the values of a hash: 我尝试从哈希值中删除所有换行符( \\n ):

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 ? 如何从%var_h的值中删除所有新行?

I tried s/\\\\n//g but I could not get it to work. 我尝试了s/\\\\n//g但无法正常工作。

s:\n::g for values %var_h;

应该可以。

What are you running the substitution against? 您要针对什么进行替代? You seem to want to fix only the values, so I would use the values keyword: 您似乎只想修复值,所以我将使用values关键字:

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: 另一种方法(应OP的要求)是使用map和slice,尽管我发现它不太清楚:

@var_h{keys %var_h} = map { s/\n//g } values %var_h;

All other solutions remove \\n from all values of hash. 所有其他解决方案将从所有哈希值中删除\\ n。

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? 从技术上讲s / \\ n // g应该足够,但是我有添加\\ r的习惯? before it, so it will handle Windows-styled new lines as well. 在此之前,它也将处理Windows样式的新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM