0

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?

3
  • ${mod} is presumably ${mode}, right? Or do you have both $mod and $mode? Commented Apr 25, 2019 at 22:23
  • mod is just a variable name. Commented Apr 25, 2019 at 22:47
  • That's why I'm wondering why you're doing ${mod} instead of $mod. Commented Apr 26, 2019 at 17:16

2 Answers 2

3

. 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"
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.