Perl syntax question (185 Views)
Reply
Advisor
hpuxrocks
Posts: 21
Registered: ‎04-07-2011
Message 1 of 6 (185 Views)
Accepted Solution

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
Acclaimed Contributor
James R. Ferguson
Posts: 21,184
Registered: ‎07-06-2000
Message 2 of 6 (185 Views)

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
James R. Ferguson
Posts: 21,184
Registered: ‎07-06-2000
Message 3 of 6 (185 Views)

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
H.Merijn Brand (procura
Posts: 6,189
Registered: ‎10-13-1997
Message 4 of 6 (185 Views)

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
hpuxrocks
Posts: 21
Registered: ‎04-07-2011
Message 5 of 6 (185 Views)

Re: Perl syntax question

thks guys
Advisor
hpuxrocks
Posts: 21
Registered: ‎04-07-2011
Message 6 of 6 (185 Views)

Re: Perl syntax question

.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.