Perl Functions Passing parameters with optional attributes

    Hello dear.

    I want to share one very simple idea and its implementation in Perl.

    The idea is this: there is a certain function to which not only the parameters are transmitted, but also the attributes of these parameters. What could it be? For example, the command and the desired query string. Or the action and the clergy of his replay.


    You can use several options. The most simple and user-friendly form, as I think, should be a solution when visually the property of a certain object is attached to the same object. Something like OOP, only easier, of course.

    What can be used for this? Hashes. The object here will act as a key, and the attribute is the hash value. Moreover, the program may even not know anything about the existence of objects and their properties - all this can and should be intercepted dynamically.

    Let's start with a simple one key, one parameter.
    The bottom line: there are several functions inside another, external. The user calls some function from the external (in our case it is simple) and passes some parameter to it. The second case is a bit more complicated. The program does not know how much and what data has been transferred to it.

    sub Simple {
    # Хэш придется сделать глобальным внутри внешней функции, чтобы
    # внутренние его видели и могли с ним работать
    our %hash = ( @_ );

    # $sub - это ключ хэша. То есть, имя запрошенной функции
    my ( $sub ) = keys( %hash );

    # Испольнить запрошенную функцию
    eval $sub or print @!;

    # Простые внутренние функции, для наглядности
    sub hello {
    my ( $name ) = values( %hash );
    printf " Hello, %s!", $name;
    }

    sub good_beye {
    my ( $name ) = values( %hash );
    printf " Good Beye, %s!", $name;
    }
    }

    &Simple( hello => 'Alex' );




    The bottom line: the program can greet a person several times in a row. Moreover, with several people, even I would say, with an infinite number of completely different people. And he greets everyone as many times as she is told. As objects, names; as parameters, the number of greetings for each name.

    sub Hello {
    # Все, что передали функции хэшем
    my %hash = ( @_ );

    # Теперь ключи хэша в массиве имен
    my @names = keys( %hash );

    # А значения - в массиве количеств повторений
    my @repeat = values( %hash );

    # Дело техники
    for( my $i=0; $i<@names; $i++ ) {
    $repeat[$i] ||= 1;
    for( my $j=0; $j<$repeat[$i]; $j++ ) {
    printf " Hello, %s!\n", $names[$i];
    }
    }
    }

    &Hello( sasha => 3, sveta => 10, Vasya );

    Also popular now: