1

I am a student learning Python as well as Perl. In our Perl program we used the code

my $param = shift;
my %local_hash = %$param;

when translating Perl to Python what would be the most similar way to 'shift' the hash or do I no longer need this part of code?

So far I have this in Python

def insert_user(local_hash):
    param = shift
    local_hash = {param}
    user_name = input("Please enter Username: ")
    user_name = user_name.replace('\n', '')
dreftymac
  • 31,404
  • 26
  • 119
  • 182
Robert
  • 47
  • 1
  • 1
  • 10
  • This seems like an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is the purpose of this code? – TigerhawkT3 Oct 07 '15 at 05:55
  • @TigerhawkT3 The purpose of this code is to add users to a hash by calling this function from another main method. – Robert Oct 07 '15 at 05:57
  • Adding to a hash - does that mean each user will be stored in a hash table, like a `set`? Oh, and that last line with `replace` isn't necessary because `input()` ends when the user presses Enter (and the trailing newline is not included). – TigerhawkT3 Oct 07 '15 at 06:02
  • @TigerhawkT3 I have a main `hash = {}` and it gets put in as `local_hash` when called with the function to keep track of users added, removed and modified via functions called by user input. And ah okay, so there is no need to find a replacement for `chomp()` that we used in perl? – Robert Oct 07 '15 at 06:04
  • I would highly recommend actually learning Python, rather than learning Perl and then trying to translate it into Python. The latter will result in very, very bad Python code. – TigerhawkT3 Oct 07 '15 at 06:06
  • In our class we are learning Perl, Python and other codes, the objective of this one was to translate from Perl to Python and this was just a part I was having trouble with. Thank you :) – Robert Oct 07 '15 at 06:08
  • 2
    That's... an incredibly bad habit to be teaching. I am sorry for you. – TigerhawkT3 Oct 07 '15 at 06:09

1 Answers1

4

You do not even need to look for alternative of shift.

In Perl subroutines are written as below:

sub foo {
    my $arg1 = shift;
    my @rest_of_args = @_;
    ...do stuff...
}

In Python you have to define the arguments the function is expecting in function definition syntax.

def foo (arg1, rest_of_args):
    ...do stuff...

Also see:

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
  • Thank you very much, so I only need to put in items I am going to use, kind of like Java? – Robert Oct 07 '15 at 06:05
  • 2
    No, not like Java. Like Python. Try the [official Python tutorial](https://docs.python.org/3.4/tutorial/index.html). – TigerhawkT3 Oct 07 '15 at 06:07
  • That Perl code posted by the OP only takes one argument (a reference to a hash), and then it makes a copy of that hash. That Python code doesn't look equivalent at all. Will changing `arg1` affect the caller? It shouldn't. The Perl code explicitly makes a copy of it. – ikegami Oct 07 '15 at 15:03