Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a string variable to a fixed string in Perl

I have a variable that is entered at a prompt:

my $name = <>;

I want to append a fixed string '_one'to this (in a separate variable).

E.g. if $name = Smith then it becomes 'Smith_one'

I have tried several various ways which do not give me the right results, such as:

my $one = "${name}_one";

^ The _one appears on the next line when I print it out and when I use it, the _one is not included at all.

Also:

my $one = $name."_one";

^ The '_one' appears at the beginning of the string.

And:

my $end = '_one';
my $one = $name.$end;
or 
my $one = "$name$end";

None of these produce the result I want, so I must be missing something related to how the input is formatted from the prompt, perhaps. Ideas appreciated!

like image 237
dgBP Avatar asked Sep 17 '12 12:09

dgBP


People also ask

How do I append a string to a string in Perl?

In general, the string concatenation in Perl is very simple by using the string operator such as dot operator (.) To perform the concatenation of two operands which are declared as variables which means joining the two variables containing string to one single string using this concatenation string dot operator (.)

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

What does $_ mean in Perl?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }


1 Answers

Your problem is unrelated to string appending: When you read a line (e.g. via <>), then the record input separator is included in that string; this is usually a newline \n. To remove the newline, chomp the variable:

    my $name = <STDIN>; # better use explicit filehandle unless you know what you are doing
    # now $name eq "Smith\n"
    chomp $name;
    # now $name eq "Smith"

To interpolate a variable into a string, you usually don't need the ${name} syntax you used. These lines will all append _one to your string and create a new string:

    "${name}_one"  # what you used
    "$name\_one"   # _ must be escaped, else the variable $name_one would be interpolated
    $name . "_one"
    sprintf "%s_one", $name
    # etc.

And this will append _one to your string and still store it in $name:

    $name .= "_one"
like image 122
amon Avatar answered Nov 23 '22 09:11

amon