BladeSystem Forums Have Moved here
To make BladeSystem information easier to find, we have moved the BladeSystem forums here, to Servers and Operating Systems.
Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

Perl syntax question

SOLVED
Go to Solution
Advisor

Perl syntax question

Hi

to insert a line in position 1 in a text file the command would be:

perl -p -i -e 'if ($. == 1) { print "Random text \n"}' $textfile

What would the correct syntax be if I wanted to pass a script variable to it to produce something like..

perl -p -i -e 'if ($. == 1) { print "Number of cars is $CARNUM \n"}' $textfile

($CARNUM being the var calculated in the script)

Many thks!

Jon
5 REPLIES
Acclaimed Contributor

Re: Perl syntax question

Hi Jon:

There are a number of ways and as always, the best choice is "it depends".

You could do:

# perl -p -i -e 'BEGIN{$CARNUM=shift};if ($. == 1) { print "Number of cars is $CARNUM \n"}' $textfile

...where you pass the variable as the first argument.

You could do:

# export CARNUM=3;perl -p -i -e 'if ($. == 1) { print "Number of cars is $ENV{CARNUM} \n"}' $textfile

Regards!

...JRF...

Acclaimed Contributor

Re: Perl syntax question

Hi (again) Jon:

I should point out that for simple one-liners you can also use alternate quoting within the Perl snippet and let the shell fill-in the interpolated variable.

Consider this example:

# X=Jon;perl -nle "print join qq( ),$X,\$_" /etc/hosts

Regards!

...JRF...
Honored Contributor

Re: Perl syntax question

Even shorter

$ perl -pi -e'1..1 and print "New line 1\n"' textfile

The default for the .. operator is the line number(s).

JRF's suggestions for $ENV{} or shift are both fine.

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Advisor

Re: Perl syntax question

thks guys
Highlighted
Advisor

Re: Perl syntax question

.