Home: Perl Programming Help: Beginner:
Substr on one liners command



Stefanik
User

Dec 5, 2012, 2:03 AM


Views: 4037
Substr on one liners command

Hi all,
I should execute a substring operation in a shell script.
I was thinking to execute the operation using perl one liners.

My code is following:

Code
$String = "Hi there"; 
$Substring = substr($String,0,2);
print "$Substring\n"


Can I execute it one liners?

Thanks


rovf
Veteran

Dec 5, 2012, 3:21 AM


Views: 4033
Re: [Stefanik] Substr on one liners command


Code
perl -le '$String = "Hi there"; $Substring = substr($String,0,2);print $Substring'


Or did I miss something in your question?????


Stefanik
User

Dec 5, 2012, 5:17 AM


Views: 4029
Re: [rovf] Substr on one liners command

Hi Rovf.
Thanks a lot! Smile


Stefanik
User

Dec 5, 2012, 6:39 AM


Views: 4026
Re: [rovf] Substr on one liners command

I've a problem to use the code with a shell variable.
Here is my code:


Code
String="some_date_interval" 

dateinterval_v=`perl -le 'print $String;$Substring = substr($String,0,4);print $Substring'`


In this way the $String print is empty.
$String is declared in unix shell.

I think there is a problem for perl module to read shell variable.


rovf
Veteran

Dec 5, 2012, 8:01 AM


Views: 4021
Re: [Stefanik] Substr on one liners command

$ENV{YOUR_SHELL_VARIABLE_GOES_HERE}


Laurent_R
Veteran / Moderator

Dec 5, 2012, 10:33 AM


Views: 4015
Re: [rovf] Substr on one liners command

In other words:


Code
String="some_date_interval"  

dateinterval_v=`perl -le '$string = ENV{String}; print $String; $Substring = substr($String,0,4); print $Substring;'`


You could also pass the value as a parameter to your Perl script:


Code
dateinterval_v=`perl -le '$string = shift; print $String; $Substring = substr($String,0,4); print $Substring;' "some_date_interval" `



rovf
Veteran

Dec 5, 2012, 12:12 PM


Views: 4011
Re: [Laurent_R] Substr on one liners command


Quote
$string = ENV{String};


Sigil is missing. Should be


Code
$string = $ENV{String};



Laurent_R
Veteran / Moderator

Dec 5, 2012, 1:49 PM


Views: 3991
Re: [rovf] Substr on one liners command

Yes of course, you are right, it should be $ENV{envrnmt_var}.


Stefanik
User

Dec 6, 2012, 12:41 AM


Views: 3985
Re: [Laurent_R] Substr on one liners command

Thanks both of you.
I try your code, but it doesn't work:


Code
String="some_date_interval"   

dateinterval_v=`perl -le '$StringPerl = $ENV{String}; print $String; print $StringPerl;$Substring = substr($StringPerl,0,4); print $Substring;'`


but the result is empty.
Instead I printout the shell variable and it has the right value.

By the way I use a "work-around" writing the variable in a temporary file, then reading that file from perl module. But this is a worst solution.


rovf
Veteran

Dec 6, 2012, 1:42 AM


Views: 3983
Re: [Stefanik] Substr on one liners command

You forgot to export your shell variable to the environment.


(This post was edited by rovf on Dec 6, 2012, 1:43 AM)