tags:

views:

97

answers:

2

I have these three lines in bash that work really nicely. I want to add them to some existing perl script but I have never used perl before ....

could somebody rewrite them for me? I tried to use them as they are and it didn't work

note that $SSH_CLIENT is a run-time parameter you get if you type set in bash (linux)

users[210]=radek       #where 210 is tha last octet from my mac's IP
octet=($SSH_CLIENT)    # split the value on spaces 
somevariable=$users[${octet[0]##*.}]        # extract the last octet from the ip address
+3  A: 

Say you have already gotten your IP in a string,

$macip = "10.10.10.123";
@s = split /\./ , $macip;
print $s[-1];  #get last octet

If you don't know Perl and you are required to use it for work, you will have to learn it. Surely you are not going to come to SO and ask every time you need it in Perl right?

ghostdog74
@ghostdog74: I promise I won't :-) I want update the existing script so instead of typing my name it will recognise it when I ssh from my machine. It reminds me.... I updated the question `$SSH_CLIENT` is a run-time parameter I can get if I type set in bash.
Radek
+3  A: 

These might work for you. I noted my assumptions with each line.

my %users = ( 210 => 'radek' ); 

I assume that you wanted a sparse array. Hashes are the standard implementation of sparse arrays in Perl.

my @octet = split ' ', $ENV{SSH_CLIENT}; # split the value on spaces

I assume that you still wanted to use the environment variable SSH_CLIENT

my ( $some_var ) = $octet[0] =~ /\.(\d+)$/; 

You want the last set of digits from the '.' to the end.

  • The parens around the variable put the assignment into list context.
  • In list context, a match creates a list of all the "captured" sequences.
  • Assigning to a scalar in a list context, means that only the number of scalars in the expression are assigned from the list.

As for your question in the comments, you can get the variable out of the hash, by:

$db = $users{ $some_var };

# OR--this one's kind of clunky...

$db = $users{ [ $octet[0] =~ /\.(\d+)$/ ]->[0] };
Axeman
@Axeman: thank you, You're assumptions are 1001% correct :-)
Radek
how can I assign my name from `%users` based on the last octet from SSH_CLIENT to a $db variable? something like `$db=$users[${octet[0]##*.}]`
Radek
it gives me this `Use of implicit split to @_ is deprecated at ./restoreSQLDb line 177.Global symbol "@octet" requires explicit package name at ./restoreSQLDb line 178.` where the lines from the code are `my $octet = split ' ', $ENV{SSH_CLIENT}; my $ddb = $users{ [ $octet[0] =~ /\.(\d+)$/ ]->[0] };`
Radek
should be `my @octet = split #...` on second line. `split` returns an array.
n0rd
@Axeman: exactly what I needed. Thank youuuuuu
Radek