Perl | Автоматическое преобразование строки в число или приведение

Опубликовано: 31 Марта, 2022

Perl имеет другой способ работы с операторами, потому что здесь оператор определяет, как будут вести себя операнды, но в других языках программирования операнды определяют поведение оператора. Приведение относится к преобразованию типа данных конкретной переменной в другой тип данных. Например, если есть строка «1234» и после преобразования ее в тип данных int, на выходе будет целое число 1234. Преобразование строки в целое число в Perl имеет много способов. Один - использовать приведение типов , а другой - использовать функцию sprintf. Иногда люди не используют преобразование слов в Perl, потому что преобразование происходит автоматически.

Приведение типов

Type conversion happens when we assign the value of one data type to another. If the data types are compatible, then Perl does Automatic Type Conversion. If not compatible, then they need to be converted explicitly which is known as Explicit Type conversion. There are two types of typecasting:

  • Implicit Typecasting: Implicit type conversion is done by the compiler itself. There is no need for the user to mention a specific type conversion using any method. The compiler on its own determines the data type of the variable if required and fixes it. In Perl when we declare a new variable and assign a value to it, it automatically converts it into a required data type.

    Example 1:

    # Perl code to demonstrate implicit 
    # type casting
      
    # variable x is of int type
    $x = 57;
      
    # variable y is of int type
    $y = 13;
      
    # z is an integer data type which
    # will contain the sum of x and y
    # implicit or automatic conversion
    $z = $x + $y;
      
    print "z is ${z} ";
      
    # type conversion of x and y integer to 
    # string due to concatenate function
    $w = $x.$y;
      
    # w is a string which has the value: 
    # concatenation of string x and string y
    print "w is ${w} ";

    Output:

    z is 70
    w is 5713
    
  • Explicit Typecasting: In this conversion the user can cast a variable to a particular data type according to requirement. Explicit type conversion is required if the programmer wants a particular variable to be of a particular data type. It is important for keeping the code consistent so that no variable causes an error due to type conversion.

    Example: The following perform explicit typecasting where a string(or any data type) is converted to specified type(say int).

    # Perl code to demonstrate Explicit 
    # type casting
      
    # String type
    $string1 = "27";
      
    # conversion of string to int 
    # using typecasting int()
    $num1 = int($string1);
      
    $string2 = "13";
      
    # conversion of string to int
    # using typecasting int()
    $num2 = int($string2);
      
    print "Numbers are $num1 and $num2 ";
      
    # applying arithmetic operators 
    # on int variables 
    $sum = $num1 + $num2;
      
    print"Sum of the numbers = $sum ";

    Output:

    Numbers are 27 and 13
    Sum of the numbers = 40
    

sprintf function

This sprintf function returns a scalar value, a formatted text string, which gets typecasted according to the code. The command sprintf is a formatter and doesn’t print anything at all.

# Perl code to demonstrate the use 
# of sprintf function
  
# string type
$string1 = "25";
  
# using sprintf to convert 
# the string to integer
$num1 = sprintf("%d", $string1);
  
$string2 = "13";
  
# using sprintf to convert 
# the string to integer
$num2 = sprintf("%d", $string2);
  
# applying arithmetic operators
# on int variables 
print "Numbers are $num1 and $num2 ";
  
$sum = $num1 + $num2;
print"Sum of the numbers = $sum ";

Output:

Numbers are 25 and 13
Sum of the numbers = 38

РЕКОМЕНДУЕМЫЕ СТАТЬИ