1752679 Members
5383 Online
108789 Solutions
New Discussion юеВ

Perl syntax question

 
SOLVED
Go to solution
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 5
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

.