(3 lines) from bash to perl? – Education Career Blog

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)

users210=radek       #where 210 is tha last octet from my mac's IP
octet=($SSH_CLIENT)    # split the value on spaces 
somevariable=$users${octet0##*.}        # extract the last octet from the ip address


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 ) = $octet0 =~ /\.(\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{  $octet0 =~ /\.(\d+)$/ ->0 };


Say you have already gotten your IP in a string,

$macip = "";
@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?

Leave a Comment