npatel
npatel

Reputation: 1111

How to assign a combination of string and a variable to another variable?

How can I assign a combination of string and a variable to another variable?

For example, I need to prepare a piece of code that I need to write in a file based on the if condition match. Here $mod and $param are variables and rest of them is just plain text that I need to write in a file.

$mode = "abc";
$param = "parameter";
if (${mod} == "xyz") {
$tmp_var = $mod #(
$param
) func_cell 
   (/*AUTO*/);
} else {
$tmp_var = $mod  func_cell 
   (/*AUTO*/);
}
# Here I will write `$tmp_var` inbetween other text in my file.

If I run above code, I see syntax errors like (Missing semicolon on previous line?). I am new to Perl. Can someone help me fixing the syntax?

Upvotes: 0

Views: 684

Answers (2)

user7712945
user7712945

Reputation:

Concatenate string by . operator for anything; constant or variable, it may be origially numeric/other type that'd be coerced into string type
some mistakes on here;

if (${mod} == "xyz") {
$tmp_var = $mod #(
$param
) func_cell 
   (/*AUTO*/);
} else {
$tmp_var = $mod  func_cell 
   (/*AUTO*/);
}

if ${mod} is meant as scalar/plain variable; it'd be $mod, {} after a variable is mostly to make use a reference
test $mod == "xyz" will be wrong if meant for string test, as it's operator are eq, ne, lt, gt, le, ge
any == != >= <= < > symbol is for numeric test
I guess you mean
$tmp_var = $mod.$func_cell
if the last is simple/scalar variable or

$tmp_var = $mod.$func_cell
if as such obtained of subroutine return

Upvotes: 0

mob
mob

Reputation: 118695

. is the string concatenation operator in Perl.

$y = "bar";
$z = "foo" . $y;
print $z;        # "foobar"

Some expressions inside pairs of "double-quotes" are also interpolated (the interpolation rules can get pretty complicated), so writing a string expression with interpolated variables is another way to concatenate strings.

$y = "bar";
$z = "foo$y";
print $z;        # "foobar";

$z = "$ybaz";    # this won't work, looks for a single var named '$ybaz'
$z = "${y}baz";  # but this will. I told you it gets complicated
print $z;        # "barbaz"

Upvotes: 3

Related Questions