Nikolay
Nikolay

Reputation: 53

Trimming carriage return (\r) in Perl

I have this simple piece of code here:

foreach my $key (keys %$structure)
{
    $key =~ s/\r?$//;
    $structure->{$key} =~ s/\r?$//;
}

This is a part of my trimming function, which takes in a reference to an object. This object (a hash, in our case) was previously initialized from the keyboard.

The problem is that each typed argument has an \r at the end, which is not very cool for outputting the structure. And even though I'm trying to substitute the \r with a regex, it just won't work. Why is that?

Upvotes: 5

Views: 643

Answers (4)

rajashekar
rajashekar

Reputation: 3753

As other answers have stated chomp removes the trailing newline character. It also works on hashes, i.e., chomp(%some_hash) removes the newline character of every value of that hash. It does not change the keys.

EDIT: It also chomps every element of an array. So you can do this:

perl -MData::Dumper -e 'my %hey = ("a\n" => "b\n", "c\n" => "d"); 
                        chomp(my @a = %hey); %hey = (@a); print Dumper(\%hey)'
$VAR1 = {
          'c' => 'd',
          'a' => 'b'
        };

This might be resource intensive if the hash is large. And "\r" is not chomped on all systems. I recommend iterating over the hash and using s(or chop if every key and value ends with "\r") as a better solution.

Upvotes: 2

OldManSeph
OldManSeph

Reputation: 2719

It's easier to use chomp the keyboard input and then use that value as a key rather than modify a key of a hash later on. If you're using STDIN in the same script than save the STDIN to a variable and wrap that in a chomp.

       chomp($variable = <STDIN>);

Then use the variable as a key.

Upvotes: 5

Ted Lyngmo
Ted Lyngmo

Reputation: 117308

You have a few syntactical errors and you also don't delete the old $key.

Something like this should work:

foreach my $key (keys %structure) {
    my $value =  $structure{$key};
    delete $structure{$key};
    $key =~ s/\r$//;
    $structure{$key} = $value;
}

Alternatively:

%structure = map { $a = $structure{$_}; s/\r$//; $_ => $a } keys %structure;

Upvotes: 3

Dri372
Dri372

Reputation: 1321

The chomp function answers your question

chomp $key
...

https://www.geeksforgeeks.org/perl-chomp-function/

Upvotes: 3

Related Questions