Simpler Navigation for Servers and Operating Systems - Please Update Your Bookmarks
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
If you have bookmarked forums or discussion boards in Servers and Operating Systems, we suggest you check and update them as needed.
cancel
Showing results for 
Search instead for 
Did you mean: 

Perl syntax question

SOLVED
Go to solution
Highlighted
hpuxrocks
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
James R. Ferguson
Acclaimed Contributor
Solution

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...

James R. Ferguson
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...
H.Merijn Brand (procura
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
hpuxrocks
Advisor

Re: Perl syntax question

thks guys
hpuxrocks
Advisor

Re: Perl syntax question

.